英文:
Updating data with $set and $sum mongodb
问题
我试图更新并汇总列的值。
await single_sku_db.collection("test").updateOne(
{ _id: ObjectId(id) },
{
$push: {
report: {
$each: [
{
name: name,
views,
},
],
$position: 0,
},
},
$set: {
report_status: "Completed",
total_views: { $sum: "$report.views" },
},
}
像这样不能像这样汇总report.views,会出现以下错误:
以美元符号($)为前缀的字段‘’对于存储无效。
是否有任何方法可以在不使用聚合的情况下执行此操作?
英文:
I was trying to do update and sum up the column value.
await single_sku_db.collection("test").updateOne(
{ _id: ObjectId(id) },
{
$push: {
report: {
$each: [
{
name: name,
views,
},
],
$position: 0,
},
},
$set: {
report_status: "Completed",
total_views: { $sum: "$report.views"},
},
}
I cant sum the report.views like this, will get this error.
> the dollar ($) prefixed field ‘’ is not valid for storage.
Is there anyway to do this without using aggregate?
答案1
得分: 2
一种选项是将$set
替换为$inc
,如下所示:
await single_sku_db.collection("test").updateOne(
{ _id: ObjectId(id) },
{
$push: {
report: {
$each: [
{
name: name,
views,
},
],
$position: 0,
},
},
$set: { report_status: "Completed" },
$inc: { total_views: views },
}
)
在playground示例中查看其运行情况。
英文:
One option is to replace the $set
with $inc
for this:
await single_sku_db.collection("test").updateOne(
{ _id: ObjectId(id) },
{
$push: {
report: {
$each: [
{
name: name,
views,
},
],
$position: 0,
},
},
$set: {report_status: "Completed"},
$inc: {total_views: views},
})
See how it works on the playground example
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论