我有我的訂單集合
[
{
_id:'134',
items:[
{
_id:'itemId1'
quantity: 2,
price: 100,,
couponsApplied:[]
},
{
_id:'itemId2'
quantity: 2,
price: 200,,
couponsApplied:[]
}
]
}
]
我想對上述每個專案應用 5% 的折扣。即在專案上_id:'itemId1',我要推送我要推送到優惠券應用為
{
couponAmount: 10, // quantity*price*percentage/100. which is 2*100*5/100
}
& 同樣在 _id:'itemId2' 上,我想推送到優惠券應用為
{
couponAmount: 20,
}
所以,在更新操作之后它應該看起來像
[
{
_id:'134',
items:[
{
_id:'itemId1'
quantity: 2,
price: 100,,
couponsApplied:[
{
_id:'100',
couponAmount: 10
}
]
},
{
_id:'itemId2'
quantity: 2,
price: 200,,
couponsApplied:[
{
_id:'1002'
couponAmount: 20,
}
]
}
]
}
]
我已經嘗試使用 $mul 和 $sum 進行聚合更新,但沒有運氣請幫忙!
uj5u.com熱心網友回復:
有點長的更新查詢。
$set- 更新items陣列欄位。1.1。
$map- 使用items陣列迭代并回傳一個陣列。1.1.1。- 將當前物件與陣列欄位
$mergeObjects合并。couponsApplied1.1.1.1。
$concatArrays-couponsApplied將陣列與1.1.1.1.1的結果組合。1.1.1.1.1。具有新檔案的陣列包含
couponAmount欄位。
db.collection.update({},
[
{
$set: {
"items": {
$map: {
input: "$items",
in: {
$mergeObjects: [
"$$this",
{
couponsApplied: {
$concatArrays: [
"$$this.couponsApplied",
[
{
couponAmount: {
$multiply: [
"$$this.price",
"$$this.quantity",
{
$divide: [
5,
100
]
}
]
}
}
]
]
}
}
]
}
}
}
}
}
])
示例 Mongo Playground
uj5u.com熱心網友回復:
試試這個:
db.collection.update({},
[
{
"$set": {
"items": {
$map: {
input: "$items",
as: "item",
in: {
_id: "$$item._id",
quantity: "$$item.quantity",
price: "$$item.price",
couponsApplied: {
$concatArrays: [
"$$item.couponsApplied",
[
{
couponAmount: {
$divide: [
{
$multiply: [
"$$item.quantity",
"$$item.price",
5
]
},
100
]
}
}
]
]
}
}
}
}
}
}
])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470265.html
