我有一個看起來像這樣的集合:
[
{
productId: 'c69b7701-c33f-4801-99f3-080450f2b6c7',
createdAt: '2021-12-04T17:33:34.221Z',
history: [{
value: 304,
storePrice: 50,
date: 1638639214000,
prevSold: {
price: 303,
createdAt: '2021-12-04T17:32:50.658Z',
},
},
...100 more records,
],
_id: '61aba66d9085f0044f96a700',
}, ...100 more records,
];
我只是用一個基本的 find 來呼叫它,即:
const slug = req.params.slug
ProductPrice.find({ productId: slug}).exec((err, data) => {
if (err){
return res.status(400).json({
error: errorHandler(err)
})
}
res.json(data)
})
我需要將上一個銷售價格與 history.value 保持在同一水平
IE:
[
{
productId: 'c69b7701-c33f-4801-99f3-080450f2b6c7',
createdAt: '2021-12-04T17:33:34.221Z',
history: [{
value: 304,
storePrice: 50,
date: 1638639214000,
prevSold: 303,
},
...100 more records,
],
_id: '61aba66d9085f0044f96a700',
},
...100 more records,
];
到目前為止,我已經嘗試了以下聚合呼叫,但它只是回傳一個空陣列。任何人都可以指出我正確的方向嗎?
ProductPrice.aggregate([
{ $match: { productId: slug } },
{ $unwind: '$history.prevSold' },
{
$addFields: {
'prevSold.value': '$price',
},
},
{
$replaceRoot: {
newRoot: '$prevSold',
},
},
]);
謝謝,
uj5u.com熱心網友回復:
使用聚合是正確的方法,這是一個使用的作業示例$map:
db.collection.aggregate([
{
$addFields: {
history: {
$map: {
input: "$history",
in: {
"$mergeObjects": [
"$$this",
{
prevSold: "$$this.prevSold.price"
}
]
}
}
}
}
}
])
蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/372908.html
上一篇:雙結構指標的分配
