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

MongoDB aggregate giới hạn subdocument theo trường projection

Dùng aggregate với $match, $unwind, $project để chỉ giữ subdocument có trường xác định.

Tạo collection demo285 với mảng details có object schema không đồng nhất:

> db.demo285.insertOne({
   "details":[
      {"Name":"Chris"},
      {"Name2":"Bob"},
      {"Name":"Mike"}
   ]
});

Pipeline: match document có details.Name, unwind, match lại subdocument có Name, project chỉ lấy Name:

> db.demo285.aggregate([
   {$match:{"details.Name":{$exists:1}}},
   {$unwind:"$details"},
   {$match:{"details.Name":{$exists:1}}},
   {$project:{"Name":"$details.Name","_id":0}}
])

Kết quả chỉ 2 subdocument có trường Name:

{"Name":"Chris"}
{"Name":"Mike"}