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

Lọc nhiều sub-document trong MongoDB với aggregation

Để lọc nhiều sub-document, sử dụng aggregate() với $unwind và $group. Tạo collection:

> db.demo200.insertOne(
   {
      "Id": "101",
      "details1": [
         { "isActive": true, "SubjectName": "MySQL" },
         { "isActive": false, "SubjectName": "Java" }
      ],
      "details2": [
         { "isActive": false, "Name": "David" },
         { "isActive": true, "Name": "Mike" }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : ObjectId("5e3c374f03d395bdc21346e4") }

Hiển thị tài liệu:

> db.demo200.find();

Kết quả:

Pipeline aggregation lọc chỉ các sub-document có isActive = true từ cả hai mảng:

> var out = [
   { "$match": { "Id": "101", "details1.isActive": true, "details2.isActive": true }},
   { "$unwind": "$details1" },
   { "$unwind": "$details2" },
   { "$match": { "details1.isActive": true, "details2.isActive": true }},
   { "$group": {
      "_id": { "_id": "$_id", "Id": "$Id" },
      "details2": { "$addToSet": "$details2" },
      "details1": { "$addToSet": "$details1" }
   }},
   { "$project": { "_id": 0, "Id": "$_id.Id", "details2": 1, "details1": 1 }}
]
> db.demo200.aggregate(out)

Kết quả - chỉ giữ sub-document active:

Quy trình: 1) Lọc tài liệu gốc, 2) Unwind hai mảng, 3) Lọc lại phần tử active, 4) Group để gom lại thành mảng, 5) Project định dạng đầu ra.