MongoDB - 如何将行复制到新创建的集合中?
要将行复制到另一个集合中,请使用 MongoDB。语法如下,其中“yourOldCollectionName”是旧集合,而“yourNewCollectionName”将获取复制,即新集合−
db.yourOldCollectionName.aggregate([{ $sample: { size: 333333 }}, {$out: "yourNewCollectionName"} ],{allowDiskUse: true});
我们首先使用文档创建集合−
> db.sourceCollection.insertOne({"EmployeeName":"Robert","EmployeeSalary":15000}); { "acknowledged" : true, "insertedId" : ObjectId("5e0397c1f5e889d7a5199506") } > db.sourceCollection.insertOne({"EmployeeName":"David","EmployeeSalary":25000}); { "acknowledged" : true, "insertedId" : ObjectId("5e0397c3f5e889d7a5199507") } > db.sourceCollection.insertOne({"EmployeeName":"Mike","EmployeeSalary":29000}); { "acknowledged" : true, "insertedId" : ObjectId("5e0397c4f5e889d7a5199508") }
以下是使用 find() 方法从集合中显示所有文档的查询−
> db.sourceCollection.find().pretty();
这将生成以下输出−
{ "_id" : ObjectId("5e0397c1f5e889d7a5199506"), "EmployeeName" : "Robert", "EmployeeSalary" : 15000 } { "_id" : ObjectId("5e0397c3f5e889d7a5199507"), "EmployeeName" : "David", "EmployeeSalary" : 25000 } { EmployeeName" : "Mike", "E"_id" : ObjectId("5e0397c4f5e889d7a5199508"), "mployeeSalary" : 29000 }
以下是创建新集合“destinationCollection”的查询−
> db.createCollection('destinationCollection'); { "ok" : 1 }
以下是将行从“sourceCollection”复制到另一个新集合“destinationCollection”的查询−
> db.sourceCollection.aggregate([{ $sample: { size: 333333 }}, {$out: "destinationCollection"} ],{allowDiskUse: true});
以下是使用 find() 方法从集合中显示所有文档的查询−
> db.destinationCollection.find().pretty()
这将生成以下输出,其中新集合从第一个集合“sourceCollection”复制了记录−
{ "_id" : ObjectId("5e0397c4f5e889d7a5199508"), "EmployeeName" : "Mike", "EmployeeSalary" : 29000 } { "_id" : ObjectId("5e0397c3f5e889d7a5199507"), "EmployeeName" : "David", "EmployeeSalary" : 25000 } { "_id" : ObjectId("5e0397c1f5e889d7a5199506"), "EmployeeName" : "Robert", "EmployeeSalary" : 15000 }
广告