Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

MongoDB Aggregate: Gộp nhiều tài liệu thành một tài liệu có mảng

Sử dụng aggregate() với $group và $push để gộp nhiều tài liệu thành một.

Tạo collection:

> db.demo248.insertOne({"id":101,"Name":"Chris","Age":21,"CountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e46b6651627c0c63e7dba6d") }
> db.demo248.insertOne({"id":101,"Name":"Bob","Age":22,"CountryName":"UK"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e46b6741627c0c63e7dba6e") }
> db.demo248.insertOne({"id":102,"Name":"Mike","Age":20,"CountryName":"AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e46b6811627c0c63e7dba6f") }

Hiển thị dữ liệu (3 tài liệu riêng biệt):

> db.demo248.find();
{ "_id" : ObjectId("5e46b6651627c0c63e7dba6d"), "id" : 101, "Name" : "Chris", "Age" : 21, "CountryName" : "US" }
{ "_id" : ObjectId("5e46b6741627c0c63e7dba6e"), "id" : 101, "Name" : "Bob", "Age" : 22, "CountryName" : "UK" }
{ "_id" : ObjectId("5e46b6811627c0c63e7dba6f"), "id" : 102, "Name" : "Mike", "Age" : 20, "CountryName" : "AUS" }

Pipeline gộp theo trường id, push toàn bộ tài liệu vào mảng details:

> db.demo248.aggregate([
...   {
...     $group : {
...       _id : "$id",
...       details : {
...         $push : {
...           id:"$id",
...           Name:"$Name",
...           Age:"$Age",
...           CountryName:"$CountryName"
...         }
...       }
...     }
...   }
...])

Kết quả: 2 tài liệu, id=101 gom 2 bản ghi, id=102 gom 1 bản ghi:

{ "_id" : 102, "details" : [ { "id" : 102, "Name" : "Mike", "Age" : 20, "CountryName" : "AUS" } ] }
{ "_id" : 101, "details" : [
  { "id" : 101, "Name" : "Chris", "Age" : 21, "CountryName" : "US" },
  { "id" : 101, "Name" : "Bob", "Age" : 22, "CountryName" : "UK" }
] }