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

Cách gộp nhiều tài liệu trong MongoDB

Gộp nhiều tài liệu trong MongoDB

Để gộp nhiều tài liệu trong MongoDB, chúng ta sử dụng phương thức aggregate(). Dưới đây là ví dụ minh họa chi tiết.

1. Tạo collection và chèn dữ liệu mẫ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" }

2. Xem tất cả tài liệu

> db.demo436.find();

Kết quả:

{ "_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 }

3. Truy vấn gộp tài liệu (aggregate pipeline)

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

4. Kết quả sau khi gộp

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

Giải thích các stage quan trọng

  • $sort: Sắp xếp tài liệu trước khi xử lý
  • $unwind: Tách mảng details thành các tài liệu riêng biệt
  • $group: Gộp theo Name, tích lũy mảng details và tính tổng Price
  • $addFields: Thêm trường mới Id và đặt lại _id
  • $project: Loại bỏ trường tạm id