Sử dụng $addFields, $reduce, $map, $divide, $concat
Pipeline aggregation phức tạp để tính toán giá trị mới từ mảng lồng nhau, chuyển đổi kiểu dữ liệu và nối chuỗi.
Dữ liệu mẫu
> db.demo719.insertOne({
Number: "7374644",
details: {
otherDetails: [
{ ProductId: "102", ProductPrice: NumberInt(500) },
{ ProductId: "103", ProductPrice: NumberInt(2000) }
]
}
});
Truy vấn Aggregation
db.demo719.aggregate([
{
$addFields: {
productPriceList: {
$reduce: {
input: {
$map: {
input: "$details.otherDetails.ProductPrice",
in: { $toString: { $divide: ["$$this", 5] } }
}
},
initialValue: "",
in: { $concat: ["$$value", "$$this", " \n "] }
}
}
}
},
{ $project: { _id: 0, Number: 1, productPriceList: 1 } }
]);
Kết quả
{ "Number": "7374644", "productPriceList": "100 \n 400 \n " }
Giá trị ProductPrice chia cho 5, chuyển thành chuỗi, rồi nối lại với dòng mới.