使用C#BsonArray在MongoDB集合中插入多个文档

时间:2016-06-14 03:54:44

标签: c# mongodb mongodb-.net-driver bson

如何使用C#中的InsertMany()MongoDB方法在Single语句中插入多个文档

我的MongoDB数据库和连接

IMongoClient _client;
IMongoDatabase _database;

_client = new MongoClient();
_database = _client.GetDatabase("test");

var collection = _database.GetCollection<BsonDocument>("EmpInfo");

我有一个收藏--BsonArray

var EmpInfoArray = new BsonArray {
    new BsonDocument
    {
        {"EmpID", "100"},
        {"EmpName", "John"},
        {"EmpMobile", new BsonArray
                        {
                            new BsonDocument { 
                                {"MobNumber", "55566610"}, 
                                {"IsPreferred", true}, 
                                {"IsLive", false}
                            },
                            new BsonDocument { 
                                {"MobNumber", "55566611"}, 
                                {"IsPreferred", true}, 
                                {"IsLive", true} 
                            },
                        }
        },
        {"IsLive", true}
    },

    new BsonDocument
    {
        {"EmpID", "101"},
        {"EmpName", "Peter"},
        {"EmpMobile", new BsonArray
                        {
                            new BsonDocument { 
                                {"MobNumber", "55566610"}, 
                                {"IsPreferred", true}, 
                                {"IsLive", false}
                            },
                            new BsonDocument { 
                                {"MobNumber", "55566611"}, 
                                {"IsPreferred", true}, 
                                {"IsLive", false} 
                            },
                        }
        },
        {"IsLive", true}
    },

    new BsonDocument
    {
        {"EmpID", "102"},
        {"EmpName", "Jack"},
        {"EmpMobile", new BsonArray
                        {
                            new BsonDocument { 
                                {"MobNumber", "55566610"}, 
                                {"IsPreferred", true}, 
                                {"IsLive", true}
                            },
                            new BsonDocument { 
                                {"MobNumber", "55566611"}, 
                                {"IsPreferred", true}, 
                                {"IsLive", true} 
                            },
                        }
        },
        {"IsLive", false}
    }

}

插入声明:

collection.InsertMany(EmpInfoArray);

在上面 InsertMany() 扩展方法中有构建错误。请帮助我如何使用C#在单个语句执行中插入多个记录。

1 个答案:

答案 0 :(得分:1)

在我的脑海中,构建错误很可能是因为InsertMany方法期望收集(IEnumerableListArray ..) BsonDocument而不是BsonArray

尝试:

var EmpInfoArray = new List<BsonDocument>() { //Changed BsonArray to List<BsonDocument>
    new BsonDocument
    {
        {"EmpID", "100"},
        {"EmpName", "John"},
        {"EmpMobile", new BsonArray
        .
        .
        .