ใช้ $addFields และ $reduce ใน Aggregate
สามารถสร้างฟิลด์ใหม่ที่เป็นสตริงต่อจากค่าราคาที่ผ่านการคำนวณ (หารด้วยตัวเลข) ได้โดยใช้ $addFields ร่วมกับ $reduce และ $map
สร้างข้อมูลตัวอย่าง
> db.demo719.insertOne({
"Number":"7374644",
"details" : {
"otherDetails" : [
{ "ProductId" :"102", "ProductPrice" : NumberInt(500) },
{ "ProductId" :"103", "ProductPrice" : NumberInt(2000) }
]
}
});
แสดงข้อมูลทั้งหมด
> db.demo719.find();
ผลลัพธ์:
{ "_id" : ObjectId("5eaae56c43417811278f5882"), "Number" : "7374644", "details" : { "otherDetails" : [ { "ProductId" : "102", "ProductPrice" : 500 }, { "ProductId" : "103", "ProductPrice" : 2000 } ] } }
คิวรีเพิ่มฟิลด์ productPriceList ที่เป็นสตริงราคาหาร 5
> 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
}
}
])
ผลลัพธ์
{ "Number" : "7374644", "productPriceList" : "100 \n 400 \n " }