arrays - 如何增加数组mongodb下重复值的计数器

标签 arrays node.js mongodb mongoose mongodb-query

我有一个像这样的 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/

相关文章:

node.js - Mongoose - 如何防止 mongoose 在模型实例化时创建 _id

ruby - Array.reject!,它是如何工作的?

node.js - Mongodb graphQL和Feather js通过_id获取数据在某些情况下返回null

javascript - 具有路由分离的 Node.js 变量作用域

Node.js - 生成的进程正在生成错误 "execvp(): No such file or directory"

node.js - 在带有 Socket.io 的 MongoDB 中使用 Change Stream 时, 'change' 被多次触发

javascript - 如何在嵌套数组中更新插入新字段

javascript - 检查嵌套数组中的元素

c - 嵌套循环比较数组中的整数

c++ - C++中的坐标系