Sử dụng $unwind trong aggregate để tách mảng subdocument, sau đó dùng hàm JS in từng dòng. Tạo collection:
> db.demo183.insertOne({
"_id": "110",
"DueDate": ISODate("2020-02-04T01:10:42.000Z"),
"ProductDetails": [
{ "ProductName": "Product-1", "isAvailable": true },
{ "ProductName": "Product-2", "isAvailable": false }
]
});
{ "acknowledged": true, "insertedId": "110" }
Hiển thị document.
Hàm in và iterator aggregate:
> var productdata = function(d) {
print(d.DueDate + ", " + d.ProductDetails.ProductName + ", " + d.ProductDetails.isAvailable);
}
> var iterator = db.demo183.aggregate([
{ $match: { _id: "110" } },
{ $unwind: '$ProductDetails' }
]);
> iterator.forEach(productdata);
Kết quả in ra console (mỗi subdocument một dòng):
Tue Feb 04 2020 06:40:42 GMT+0530, Product-1, true Tue Feb 04 2020 06:40:42 GMT+0530, Product-2, false