Để lấy các phần tử cụ thể từ mảng lồng nhau, sử dụng $unwind kết hợp $match với dot notation trong pipeline aggregate.
Tạo collection sản phẩm với mảng thông tin
> db.demo641.insert({
ProductId: 101,
"ProductInformation": [
{ ProductName: "Product-1", ProductPrice: 1000 },
{ ProductName: "Product-2", ProductPrice: 500 },
{ ProductName: "Product-3", ProductPrice: 2000 },
{ ProductName: "Product-4", ProductPrice: 3000 }
]
});
Hiển thị document gốc
> db.demo641.find();
Kết quả:
{
"_id" : ObjectId("5e9c31d46c954c74be91e6e2"),
"ProductId" : 101,
"ProductInformation" : [
{ "ProductName" : "Product-1", "ProductPrice" : 1000 },
{ "ProductName" : "Product-2", "ProductPrice" : 500 },
{ "ProductName" : "Product-3", "ProductPrice" : 2000 },
{ "ProductName" : "Product-4", "ProductPrice" : 3000 }
]
}
Aggregate lọc sản phẩm giá 1000 hoặc 2000
> db.demo641.aggregate([
{ $unwind: "$ProductInformation" },
{ $match: { "ProductInformation.ProductPrice": { $in: [1000, 2000] } } },
{ $project: { _id: 0, ProductInformation: 1 } }
]).pretty();
Kết quả (2 sản phẩm khớp):
{
"ProductInformation" : { "ProductName" : "Product-1", "ProductPrice" : 1000 }
}
{
"ProductInformation" : { "ProductName" : "Product-3", "ProductPrice" : 2000 }
}
Giải thích:
$unwind: Phân rã mảng ProductInformation → 4 document riêng biệt$matchvới$in: Lọc giữ ProductPrice = 1000 HOẶC 2000$project: Chỉ hiển thị ProductInformation, ẩn _id
Cách này cho phép truy vấn, lọc, biến đổi từng phần tử mảng như document độc lập.