Sử dụng aggregation pipeline để đếm số giá trị duy nhất của trường OtherDetails trong nhóm Group-1. Tạo collection:
> db.demo718.insertOne({
... "id":101,
... "details": {
... "OtherDetails": ["Chris", "Mike", "Sam"],
... "GroupName": ["Group-1"],
... "Info": []
... }
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5eaae25843417811278f5880") }
> db.demo718.insertOne({
... "id":102,
... "details": {
... "OtherDetails": ["Chris", "David"],
... "GroupName": ["Group-1"],
... "Info": []
... }
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5eaae25943417811278f5881") }
Hiển thị dữ liệu:
> db.demo718.find();
{ "_id" : ObjectId("5eaae25843417811278f5880"), "id" : 101, "details" : { "OtherDetails" : [ "Chris", "Mike", "Sam" ], "GroupName" : [ "Group-1" ], "Info" : [ ] } }
{ "_id" : ObjectId("5eaae25943417811278f5881"), "id" : 102, "details" : { "OtherDetails" : [ "Chris", "David" ], "GroupName" : [ "Group-1" ], "Info" : [ ] } }
Pipeline aggregation đếm giá trị duy nhất:
> db.demo718.aggregate([
... { $unwind: "$details.GroupName" },
... { $match: { "details.GroupName": "Group-1" } },
... { $unwind: "$details.OtherDetails" },
... { $group: {
... _id: "$details.GroupName",
... OtherDetailsUnique: { $addToSet: "$details.OtherDetails" }
... }},
... { $project: {
... _id: 0,
... GROUP_NAME: "$_id",
... OtherDetailsUniqueCount: { $size: "$OtherDetailsUnique" }
... }}
... ]);
Kết quả:
{ "GROUP_NAME" : "Group-1", "OtherDetailsUniqueCount" : 4 }
Giải thích pipeline:
$unwind GroupName: Phân tách mảng GroupName$match: Lọc nhóm "Group-1"$unwind OtherDetails: Phân tách mảng tên$group + $addToSet: Thu thập tên duy nhất (tự động loại trùng)$project + $size: Đếm số lượng tên duy nhất