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

Lấy trường từ nhiều sub-document khớp điều kiện trong MongoDB

Để trích xuất trường từ nhiều sub-document thỏa mãn điều kiện, dùng aggregation $unwind phân tách mảng, $match lọc, $project chọn trường. Tạo collection phức tạp:

> db.demo671.insertOne({
  "details": [
    { "id": "1" },
    { CountryName: "US", "details1": [ { "id": "1" }, { "id": "2" } ] },
    { CountryName: "UK", "details1": [ { "id": "2" }, { "id": "1" } ] },
    { CountryName: "AUS", "details1": [ { "id": "1" } ] }
  ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea3e5d004263e90dac943e0") }

Hiển thị dữ liệu:

> db.demo671.find();

Kết quả:

Pipeline: $unwind details, $match lọc details.details1.id = "1", $project lấy CountryName:

> db.demo671.aggregate([
  {$unwind: '$details'},
  {$match: {'details.details1.id': '1'}},
  {$project: {_id: 0, Country: '$details.CountryName'}}
]).pretty()

Kết quả - 3 quốc gia có details1 chứa id="1":

Giải thích: $unwind biến mảng details (4 phần tử) thành 4 tài liệu. Phần tử đầu tiên {id:"1"} không có details1 nên bị loại bởi $match. 3 phần tử còn lại có details1 chứa id="1" nên được giữ lại. $project chỉ chọn CountryName.

Thay thế (MongoDB 3.2+): Dùng $filter trong $project để không unwind, giữ cấu trúc mảng.