Ankit
Ankit

Reputation: 1011

How to increase counter on repetition of value under an array mongodb

I have a mongoose schema like this:

{
    "_id" : ObjectId("5a7acda13b808dbed05d6505"),
    "symbol" : "@AKS",
    "counter" : 4
},
{
    "_id" : ObjectId("5a7acda13b808dbed05d6506"),
    "symbol" : "@AKD",
    "counter" : 5
}

Now if I want to update multiple column i.e "symbol" values on one query then MongoDB updateMany Query will do. This is Query:

MyCollectionName.updateMany({ 'symbol' : { $in : req.body.array}}, { $inc : { 'counter': 1 } }, function(err, data) {
                if(err) {
                    console.log('error')
                } else {
                    console.log('value incremented')
                }
            });

By this Query If I give the Array value i.e

var array = ["@AKS", "@AKD"];

Then it will Increment the counter of Both. My Question is If I will Provide the Same value on an array then I want Two increment not one. Like this:

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

But currently it will do Only One. Is this possible???? Any help is really appreciated.

Upvotes: 1

Views: 77

Answers (2)

chridam
chridam

Reputation: 103445

You can use the bulkWrite API for this update as it allows you to compose an array of bulkWrite() write operations in which you can use the updateOne operation for each element in the array. The following example shows how you can apply it in your case:

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

Upvotes: 1

t3__rry
t3__rry

Reputation: 2849

what if instead of using updateMany you just forEach your array:

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

Upvotes: 0

Related Questions