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#.
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
.
.
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.