1

How can I increment the value of an specific element of an array of a MongoDB document in Meteor or nodeJS?

Say, I've following document:

{
    "_id" : "4tP6ewe4Z5kwYA3Je",
    "name" : "chutia",
    "address" : "shonir akhra",
    "itemCount" : "4",
    "items" : [ 
        "3", 
        "4",
        "13", 
        "24"
    ]
}

I need to increment the n'th element of items array. Where n is a variable.

Mostafiz Rahman
  • 8,169
  • 7
  • 57
  • 74

2 Answers2

2

The right way to do this is:

{$inc: {[`items.${idx}`]: 1}}

Where idx is the array index. Courtesy MasterAM's comment

Community
  • 1
  • 1
Mostafiz Rahman
  • 8,169
  • 7
  • 57
  • 74
  • does this type of syntax have a name (or is the convention documented somewhere?) - ie the array containing a template string - i've never seen it before, it took me a while to figure out what i was looking at! i still don't understand how/why the "array brackets" make the key name acceptable. (it did work for me though!) – user1063287 Jun 22 '19 at 11:09
  • update to earlier comment if it helps anyone else - it seems it is a "computed key", see: https://stackoverflow.com/a/30969495 and https://stackoverflow.com/a/2274327 and https://stackoverflow.com/a/19837961 – user1063287 Jun 22 '19 at 11:15
1

As documented here https://docs.mongodb.com/manual/reference/operator/update/inc/, you can increment an element in an array by dot notation.

The following example increase the first element of items by 1.

db.<collection>.update(
 <query>,
 { $inc: { "items.0": 1 } }
)
legendecas
  • 359
  • 2
  • 8