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

Làm cách nào để hợp nhất nhiều tài liệu trong MongoDB?

Để hợp nhất nhiều tài liệu trong MongoDB, hãy sử dụng tổng hợp (). Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -

> db.demo436.insertOne(
...    {
...       "_id" : "101",
...       "Name": "Chris",
...       "details" : [
...          {
...             "CountryName" : "US",
...             "Age" : 21
...          }
...       ],
...       "Price" : 50
...    }
... );
{ "acknowledged" : true, "insertedId" : "101" }
> db.demo436.insertOne(
...    {
...       "_id" : "102",
...       "Name": "Chris",
...       "details" : [
...          {
...             "CountryName" : "UK",
...             "Age" : 22
...          }
...       ],
...       "Price" : 78
...    }
... );
{ "acknowledged" : true, "insertedId" : "102" }
> db.demo436.insertOne(
...    {
...       "_id" : "103",
...       "Name": "Chris",
...       "details" : [
...          {
...             "CountryName" : "US",
...             "Age" : 21
...          }
...       ],
..      . "Price" : 50
...    }
... );
{ "acknowledged" : true, "insertedId" : "103" }

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.demo436.find();

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

{ "_id" : "101", "Name" : "Chris", "details" : [ { "CountryName" : "US", "Age" : 21 } ], "Price" : 50 }
{ "_id" : "102", "Name" : "Chris", "details" : [ { "CountryName" : "UK", "Age" : 22 } ], "Price" : 78 }
{ "_id" : "103", "Name" : "Chris", "details" : [ { "CountryName" : "US", "Age" : 21 } ], "Price" : 50 }

Sau đây là truy vấn để hợp nhất nhiều tài liệu trong MongoDB -

> db.demo436.aggregate([
...    {$sort: {_id: 1, Name: 1}},
...    {$unwind: '$details'},
...    {$group: {_id: '$Name', details: {$push: '$details'},
...    Price: {$sum: '$Price'},
...    id: {$last: {$concat: ["$_id", "_", "AppendedValue" ]}},
...    Name: {$last: '$Name'}}},
...    {$addFields: {Id: 'NewIdAppped', _id: '$id'}},
...    {$project: {"id": 0 }}])

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

{ "_id" : "103_AppendedValue", "details" : [ { "CountryName" : "US", "Age" : 21 }, { "CountryName" : "UK", "Age" : 22 }, { "CountryName" : "US", "Age" : 21 } ], "Price" : 178, "Name" : "Chris", "Id" : "NewIdAppped" }