我有一个像这样的 Mongoose 模式:
{
"_id" : ObjectId("5a7acda13b808dbed05d6505"),
"symbol" : "@AKS",
"counter" : 4
},
{
"_id" : ObjectId("5a7acda13b808dbed05d6506"),
"symbol" : "@AKD",
"counter" : 5
}
现在,如果我想更新一个查询上的多个列,即“符号”值,那么 MongoDB updateMany Query 就可以了。这是查询:
MyCollectionName.updateMany({ 'symbol' : { $in : req.body.array}}, { $inc : { 'counter': 1 } }, function(err, data) {
if(err) {
console.log('error')
} else {
console.log('value incremented')
}
});
通过此查询如果我给出数组值,即
var array = ["@AKS", "@AKD"];
然后它将增加两者的计数器。我的问题是,如果我在数组上提供相同的值,那么我想要两个增量而不是一。像这样:
var array = ["@AKS", "@AKS"];
//I want the Increment of 2.
var array = [@AKS", "@AKS", "@AKS", "@AKS"]
//at this stage I want the counter of Increment is 4
但目前它只能做一个。这可能吗???? 非常感谢任何帮助。
最佳答案
您可以使用bulkWrite
此更新的 API,因为它允许您组成 bulkWrite()
的数组 写入操作,您可以在其中使用 updateOne
对数组中的每个元素进行操作。以下示例展示了如何将其应用到您的案例中:
let ops = [];
const handleResult = res => console.log(res);
const handleError = err => console.error(err);
req.body.array.forEach(function(item) {
ops.push({
"updateOne": {
"filter": { "symbol": item },
"update": { "$inc": { "counter": 1 } }
}
});
if (ops.length === 1000) {
MyCollectionName.bulkWrite(ops).then(handleResult).catch(handleError);
ops = [];
}
})
if (ops.length > 0) MyCollectionName.bulkWrite(ops).then(handleResult).catch(handleError);
关于arrays - 如何增加数组mongodb下重复值的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49507637/