MediaMaker
MediaMaker

Reputation: 110

In MongoDB, how do I increase multiple values?

The database document looks like :

{   "_id" : 12345,
    "options" : [ 
        {
            "no" : 1,
            "apples" : 0
        }, 
        {
            "no" : 2,
            "apples" : 0
        }, 
        {
            "no" : 3,
            "apples" : 0
        }
    ]
}

and I want(with one query) to increment apples on only say numbers 1 and 3, each by one. Thanks.

Upvotes: 0

Views: 241

Answers (1)

Vijay Rajpurohit
Vijay Rajpurohit

Reputation: 1352

You can use the arrayFilters for updating the fields in an array:

here is the query I wrote to update the values:

db.sample.update(
  {},
  {
    $inc:{
      "options.$[options].apples":1
    }
  },
  {
    arrayFilters:[
      {
        "options.no":{
          $in:[1,3]
        }
      }
    ]
  }
)

You can set your filters in arrayFilters according to your requirements.

For more about arrayFilters read here.

Hope this will help :)

Upvotes: 1

Related Questions