【问题标题】:How to increase counter on repetition of value under an array mongodb如何在数组mongodb下增加重复值的计数器
【发布时间】:2018-09-05 13:15:57
【问题描述】:

我有一个像这样的猫鼬模式:

{
    "_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"];

然后它会增加Both的计数器。我的问题是如果我将在数组上提供相同的值,那么我想要两个增量而不是一个。像这样:

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

但目前它只会做一个。这可能吗???? 非常感谢任何帮助。

【问题讨论】:

    标签: arrays node.js mongodb mongoose mongodb-query


    【解决方案1】:

    您可以使用 bulkWrite API 进行此更新,因为它允许您编写一组 bulkWrite() 写入操作,您可以在其中使用 @987654323数组中每个元素的@操作。以下示例显示了如何在您的案例中应用它:

    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);
    

    【讨论】:

      【解决方案2】:

      如果不使用updateMany 而只是forEach 你的数组会怎样:

      const yourArray = req.body.array;
      yourArray.forEach(function(item) {
         MyCollectionName.update({ 'symbol': { $in: item }}, { $inc: { 'counter': 1 }, function (err, data) {
          // additional code
        }); 
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-24
        • 2022-01-22
        • 2018-03-23
        • 2021-12-25
        • 1970-01-01
        • 1970-01-01
        • 2013-10-30
        • 1970-01-01
        相关资源
        最近更新 更多