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

Triển khai MongoDB Aggregate: $unwind, $group và $project

$unwind phân rã trường mảng thành nhiều tài liệu riêng biệt cho từng phần tử.
$group nhóm tài liệu theo biểu thức _id và xuất ra một tài liệu cho mỗi nhóm.
$project truyền tài liệu với các trường được yêu cầu sang stage tiếp theo.

Tạo collection với mảng details chứa trường isActive:

> db.demo238.insertOne({
...   "EmailId" : "John@gmail.com",
...   "details" : [ { "Name" : "Bob", "isActive" : true } ]
...});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4418e3f4cebbeaebec5152") }
> db.demo238.insertOne({
...   "EmailId" : "Chris@gmail.com",
...   "details" : [ { "Name" : "David" } ]
...});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4418e3f4cebbeaebec5153") }
> db.demo238.insertOne({
...   "EmailId" : "Mike@gmail.com",
...   "details" : [ { "Name" : "Carol", "isActive" : true } ]
...});
{ "acknowledged" : true, "insertedId" : ObjectId("5e4418e4f4cebbeaebec5154") }

Hiển thị dữ liệu gốc:

> db.demo238.find().pretty();
{ "_id" : ObjectId("5e4418e3f4cebbeaebec5152"), "EmailId" : "John@gmail.com", "details" : [ { "Name" : "Bob", "isActive" : true } ] }
{ "_id" : ObjectId("5e4418e3f4cebbeaebec5153"), "EmailId" : "Chris@gmail.com", "details" : [ { "Name" : "David" } ] }
{ "_id" : ObjectId("5e4418e4f4cebbeaebec5154"), "EmailId" : "Mike@gmail.com", "details" : [ { "Name" : "Carol", "isActive" : true } ] }

Pipeline aggregation: lọc isActive=true, unwind mảng, lọc lại, nhóm theo Name:

> db.demo238.aggregate([
...   { "$match": { "details.isActive": true } },
...   { "$unwind": "$details" },
...   { "$match": { "details.isActive": true } },
...   { "$group": {
...     "_id": "$details.Name",
...     "active": { "$first": "$_id" }
...   }}
...]);

Kết quả chỉ lấy Bob và Carol (có isActive=true):

{ "_id" : "Carol", "active" : ObjectId("5e4418e4f4cebbeaebec5154") }
{ "_id" : "Bob", "active" : ObjectId("5e4418e3f4cebbeaebec5152") }