要在MongoDB中批量插入,请使用initializeUnorderedBulkOp()
。让我们创建一个包含文档的集合-
> var bulkInsertDoc = db.demo663.initializeUnorderedBulkOp();
> bulkInsertDoc.insert( { Name: "John",CountryName:"US"} );
> bulkInsertDoc.insert( { Name: "Chris",CountryName:"UK"} );
> bulkInsertDoc.insert( { Name: "David",CountryName:"AUS"} );
> bulkInsertDoc.execute();
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
在find()
方法的帮助下显示集合中的所有文档-
> db.demo663.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea1b41424113ea5458c7d05"), "Name" : "John", "CountryName" : "US" }
{ "_id" : ObjectId("5ea1b41424113ea5458c7d06"), "Name" : "Chris", "CountryName" : "UK" }
{ "_id" : ObjectId("5ea1b41424113ea5458c7d07"), "Name" : "David", "CountryName" : "AUS" }