问题
How to Insert more than one document in a Single statement using InsertMany() MongoDB Method in C#
My MongoDB Database and Connections
IMongoClient _client;
IMongoDatabase _database;
_client = new MongoClient();
_database = _client.GetDatabase("test");
var collection = _database.GetCollection<BsonDocument>("EmpInfo");
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}
}
}
The Insert Statement:
collection.InsertMany(EmpInfoArray);
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#.
回答1:
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
.
try :
var EmpInfoArray = new List<BsonDocument>() { //Changed BsonArray to List<BsonDocument>
new BsonDocument
{
{"EmpID", "100"},
{"EmpName", "John"},
{"EmpMobile", new BsonArray
.
.
.
来源:https://stackoverflow.com/questions/37802690/insertmany-document-in-a-mongodb-collection-using-c-sharp-bsonarray