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

MongoDB GroupBy thiết lập trạng thái (status) với aggregate

Sử dụng aggregate với $cond, $push, $setDifference để phân loại document theo giá trị Status.

Tạo collection demo149:

> db.demo149.insertOne({"Status":40});
> db.demo149.insertOne({"Status":40});
> db.demo149.insertOne({"Status":50});

Pipeline phức tạp: group push có điều kiện vào mảng done/notdone, rồi loại bỏ false với $setDifference:

> db.demo149.aggregate([
   {
      "$group": {
         "_id": null,
         "done": {
            "$push": {
               "$cond": [
                  {"$eq":["$Status",40]},
                  {"_id":"$_id","Status":"$Status"},
                  false
               ]
            }
         },
         "notdone": {
            "$push": {
               "$cond": [
                  {"$eq":["$Status",50]},
                  {"_id":"$_id","Status":"$Status"},
                  false
               ]
            }
         }
      }
   },
   {
      "$project": {
         "_id":0,
         "done": {"$setDifference":["$done",[false]]},
         "notdone": {"$setDifference":["$notdone",[false]]}
      }
   }
]);

Kết quả phân tách 2 nhóm:

{
   "done" : [
      {"_id":ObjectId("5e350386fdf09dd6d08539c4"),"Status":40},
      {"_id":ObjectId("5e350388fdf09dd6d08539c5"),"Status":40}
   ],
   "notdone" : [
      {"_id":ObjectId("5e35038afdf09dd6d08539c6"),"Status":50}
   ]
}