Computer >> Máy Tính >  >> Lập trình >> MongoDB

MongoDB - Làm cách nào để sao chép các hàng vào một bộ sưu tập mới được tạo?

Để sao chép các hàng vào một bộ sưu tập khác, hãy sử dụng MongoDB. Cú pháp như sau, trong đó “yourOldCollectionName” là bộ sưu tập cũ, trong khi nơi bộ sưu tập này sẽ được sao chép là bộ sưu tập mới của chúng tôi, tức là “yourNewCollectionName” -

db.yourOldCollectionName.aggregate([{ $sample: { size: 333333 }}, {$out: "yourNewCollectionName"} ],{allowDiskUse: true});

Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

> 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")
}

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

> db.sourceCollection.find().pretty();

Điều này sẽ tạo ra kết quả sau -

{
   "_id" : ObjectId("5e0397c1f5e889d7a5199506"),
   "EmployeeName" : "Robert",
   "EmployeeSalary" : 15000
}
{
   "_id" : ObjectId("5e0397c3f5e889d7a5199507"),
   "EmployeeName" : "David",
   "EmployeeSalary" : 25000
}
{
   EmployeeName" : "Mike",
   "E"_id" : ObjectId("5e0397c4f5e889d7a5199508"),
   "mployeeSalary" : 29000
}

Đây là truy vấn để tạo một bộ sưu tập mới “destinationCollection” -

> db.createCollection('destinationCollection');
{ "ok" : 1 }

Sau đây là truy vấn để sao chép các hàng từ “sourceCollection” sang một bộ sưu tập mới khác “destinationCollection” -

> db.sourceCollection.aggregate([{ $sample: { size: 333333 }}, {$out: "destinationCollection"} ],{allowDiskUse: true});

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -

> db.destinationCollection.find().pretty()

Điều này sẽ tạo ra kết quả sau, trong đó bộ sưu tập mới được sao chép các bản ghi từ bộ sưu tập đầu tiên “sourceCollection” -

{
   "_id" : ObjectId("5e0397c4f5e889d7a5199508"),
   "EmployeeName" : "Mike",
   "EmployeeSalary" : 29000
}
{
   "_id" : ObjectId("5e0397c3f5e889d7a5199507"),
   "EmployeeName" : "David",
   "EmployeeSalary" : 25000
}
{
   "_id" : ObjectId("5e0397c1f5e889d7a5199506"),
   "EmployeeName" : "Robert",
   "EmployeeSalary" : 15000
}