我使用以下查询来更新mongodb中的文档,但它抛出了错误The dollar ($) prefixed field '$subtract' in 'abc.$subtract' is not valid for storage.
const bulkUpdate = arrs.map(arr => {
const { val = 0 } = arr
return {
updateMany: {
filter: {
date: 20201010
},
update: {
$set: {
abc: {
$subtract: [val, { $add: [{ $ifNull: ['$a1', 0] }, { $ifNull: ['$b1', 0] } ] }]
}
},
},
},
}
})
if (bulkUpdate.length > 0) {
return mongoConnection.pool
.db('test')
.collection('testTable')
.bulkWrite(bulkUpdate)
}感谢就是进步
发布于 2020-11-02 23:41:19
$subtract和$ifNull不是update操作符,因此您不能在update中使用它们(除了在流水线update中)。
如果你使用的是Mongo版本的4.2+,你可以使用管道更新而不是“文档更新”,如下所示:
{
updateMany: {
filter: {
date: 20201010
},
update: [
{
$set: {
abc: {
$subtract: [val, {$add: [{$ifNull: ['$a1', 0]}, {$ifNull: ['$b1', 0]}]}]
}
}
}
]
}
}如果不是这样,那么您将不得不读取每个文档并单独更新它,就像4.2版之前一样,您不能在更新时访问文档字段,因为您正在尝试这样做。
https://stackoverflow.com/questions/64648271
复制相似问题