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

MongoDB Aggregation với nhiều khóa (multiple keys)

Sử dụng $group với _id là đối tượng chứa nhiều khóa (Name và năm của DueDate). Tạo collection:

> db.demo190.insertOne({
  "DueDate": ISODate("2020-01-01"), "Value": 10, "Name": "Chris"
});
{ "acknowledged": true, "insertedId": ObjectId("5e3ad76403d395bdc21346bf") }
> db.demo190.insertOne({
  "DueDate": ISODate("2020-02-05"), "Value": 30, "Name": "David"
});
{ "acknowledged": true, "insertedId": ObjectId("5e3ad76403d395bdc21346c0") }
> db.demo190.insertOne({
  "DueDate": ISODate("2020-01-01"), "Value": 40, "Name": "Chris"
});
{ "acknowledged": true, "insertedId": ObjectId("5e3ad7f003d395bdc21346c1") }

Hiển thị document.

Pipeline aggregate nhóm theo Name và năm (extract bằng $year), tính tổng Value:

> db.demo190.aggregate([
  {
    "$group": {
      "_id": { "Name": "$Name", "DueDate": { "$year": "$DueDate" } },
      "Value": { "$sum": "$Value" }
    }
  }
]);

Kết quả (tổng Value theo Name và năm):

{ "_id": { "Name": "David", "DueDate": 2020 }, "Value": 30 }
{ "_id": { "Name": "Chris", "DueDate": 2020 }, "Value": 50 }