Để 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:
$unwinddetails,$matchlọc details.details1.id = "1",$projectlấ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:
$unwindbiế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.$projectchỉ chọn CountryName.Thay thế (MongoDB 3.2+): Dùng
$filtertrong $project để không unwind, giữ cấu trúc mảng.