使用C#BsonArray将MongoDB集合中的InsertMany文档 [英] InsertMany Document in a MongoDB Collection using C# BsonArray
问题描述
如何在C#中使用InsertMany()MongoDB方法在单个语句中插入多个文档
How to Insert more than one document in a Single statement using InsertMany() MongoDB Method in C#
我的MongoDB数据库和连接
My MongoDB Database and Connections
IMongoClient _client;
IMongoDatabase _database;
_client = new MongoClient();
_database = _client.GetDatabase("test");
var collection = _database.GetCollection<BsonDocument>("EmpInfo");
我正在收藏-BsonArray
I'm having a Collection - 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#在单个语句执行中插入多个记录.
In the above InsertMany()
Extended method has a build error. Kindly assist me how to insert multiple records in a single statement execution using C#.
推荐答案
最重要的是,生成错误很可能是因为InsertMany
方法需要一个集合(IEnumerable
,List
或Array
..),而不是BsonArray
.
Off the top of my head, the build error is most probably because the InsertMany
method is expecting a collection (IEnumerable
,List
or Array
..) of BsonDocument instead of a BsonArray
.
尝试:
var EmpInfoArray = new List<BsonDocument>() { //Changed BsonArray to List<BsonDocument>
new BsonDocument
{
{"EmpID", "100"},
{"EmpName", "John"},
{"EmpMobile", new BsonArray
.
.
.
这篇关于使用C#BsonArray将MongoDB集合中的InsertMany文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!