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

Áp dụng toán tử tích lũy $first trên biến $$ROOT trong MongoDB

Các toán tử tích lũy (accumulators) duy trì trạng thái khi tài liệu đi qua pipeline. Biến $$ROOT tham chiếu đến tài liệu gốc (root document) đang được xử lý.

Tạo collection với ngày tạo:

> db.demo582.insertOne({FirstName:"Chris",Age:21,createDate:new ISODate("2020-01-10")});
{ "acknowledged" : true, "insertedId" : ObjectId("5e91ce41fd2d90c177b5bcbd") }
> db.demo582.insertOne({FirstName:"Chris",Age:21,createDate:new ISODate("2020-04-21")});
{ "acknowledged" : true, "insertedId" : ObjectId("5e91ce4ffd2d90c177b5bcbe") }
> db.demo582.insertOne({FirstName:"Chris",Age:22,createDate:new ISODate("2020-02-11")});
{ "acknowledged" : true, "insertedId" : ObjectId("5e91ce59fd2d90c177b5bcbf") }
> db.demo582.insertOne({FirstName:"Chris",Age:22,createDate:new ISODate("2020-01-12")});
{ "acknowledged" : true, "insertedId" : ObjectId("5e91ce6efd2d90c177b5bcc0") }

Hiển thị dữ liệu:

> db.demo582.find();
{ "_id" : ObjectId("5e91ce41fd2d90c177b5bcbd"), "FirstName" : "Chris", "Age" : 21, "createDate" : ISODate("2020-01-10T00:00:00Z") }
{ "_id" : ObjectId("5e91ce4ffd2d90c177b5bcbe"), "FirstName" : "Chris", "Age" : 21, "createDate" : ISODate("2020-04-21T00:00:00Z") }
{ "_id" : ObjectId("5e91ce59fd2d90c177b5bcbf"), "FirstName" : "Chris", "Age" : 22, "createDate" : ISODate("2020-02-11T00:00:00Z") }
{ "_id" : ObjectId("5e91ce6efd2d90c177b5bcc0"), "FirstName" : "Chris", "Age" : 22, "createDate" : ISODate("2020-01-12T00:00:00Z") }

Pipeline: Nhóm theo FirstName, lấy ngày max, đếm số lượng, và lấy tài liệu gốc đầu tiên ($first + $$ROOT):

> db.demo582.aggregate([
...   { "$group": {
...     "_id": "$FirstName",
...     "MaximumDate": { "$max": "$createDate" },
...     "count": { "$sum": 1 },
...     "details": { "$first": "$$ROOT" }
...   }},
...   { "$project": {
...     "MaximumDate": 1, "count": 1,
...     "details": { "_id": "$_id", "FirstName": "$details.FirstName", "Age": "$details.Age" }
...   }}
... ]);

Kết quả:

{ "_id" : "Chris", "MaximumDate" : ISODate("2020-04-21T00:00:00Z"), "count" : 4, "details" : { "_id" : "Chris", "FirstName" : "Chris", "Age" : 21 } }

Giải thích: $first: "$$ROOT" lấy toàn bộ tài liệu gốc đầu tiên trong mỗi nhóm (theo thứ tự pipeline). Kết hợp $sort trước $group để kiểm soát tài liệu nào được chọn làm "first".