Trích xuất phần tử khớp từ mảng lồng sâu
Kết hợp $project, $filter, $map để lọc và reshape mảng lồng nhau phức tạp.
Dữ liệu 3 cấp lồng nhau
> db.demo342.insertOne({
"Id": "101",
"details1": {
"details2": [{
"details3": [
{"Name": "Mike", "CountryName": "US"},
{"Name": "David", "CountryName": "AUS"},
{"Name": "Bob", "CountryName": "UK"}
]
}]
}
});
Pipeline lọc Name = "Bob"
> db.demo342.aggregate([
{
$project: {
"details1": {
"details2": {
$filter: {
input: {
$map: {
input: "$details1.details2",
in: {
"details3": {
$filter: {
input: "$$this.details3",
cond: { $eq: ["$$this.Name", "Bob"] }
}
}
}
}
},
cond: { $ne: ["$$this.details3", []] }
}
}
}
}
}
]);
Kết quả
{
"_id": ObjectId("..."),
"details1": {
"details2": [{
"details3": [{ "Name": "Bob", "CountryName": "UK" }]
}]
}
}
Giải thích: $map duyệt qua details2, $filter bên trong lọc details3, $filter bên ngoài loại bỏ details2 rỗng.