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

Triển khai $match và $project trong MongoDB aggregate

$match lọc tài liệu để chỉ chuyển tiếp những tài liệu khớp điều kiện đến stage tiếp theo.

$project chuyển tiếp tài liệu với các trường được yêu cầu đến stage tiếp theo trong pipeline.

Tạo collection:

> db.demo545.insert({Name:"Chris",details:{SubjectScore1:56,SubjectScore2:56}})
WriteResult({ "nInserted" : 1 })
> db.demo545.insert({Name:"David",details:{SubjectScore1:78,SubjectScore2:78}})
WriteResult({ "nInserted" : 1 })

Hiển thị tất cả:

> db.demo545.find();

Kết quả:

{ "_id" : ObjectId("5e8e246e9e5f92834d7f05d5"), "Name" : "Chris", "details" : { "SubjectScore1" : 56, "SubjectScore2" : 56 } }
{ "_id" : ObjectId("5e8e24709e5f92834d7f05d6"), "Name" : "David", "details" : { "SubjectScore1" : 78, "SubjectScore2" : 78 } }

Pipeline aggregate: $match rỗng (lấy tất), $project chọn SubjectScore1 và đổi tên SubjectScore2 thành "out", sau đó $group theo "out":

>db.demo545.aggregate([{$match:{}},{$project:{"_id":0,"details.SubjectScore1":1,out:"$details.SubjectScore2"}},{$group:{_id:"$out"}}])

Kết quả (giá trị duy nhất của SubjectScore2):

{ "_id" : 78 }
{ "_id" : 56 }