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.

2 Answers 2

2

The right way to do this is:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

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!)
update to earlier comment if it helps anyone else - it seems it is a "computed key", see: stackoverflow.com/a/30969495 and stackoverflow.com/a/2274327 and stackoverflow.com/a/19837961
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 } }
)

2 Comments

In my case the index of the array will be a variable. So, "items.0" won't work I guess. How to deal with this?
{$inc: {[`items.${idx}`]: 1}}, where idx is your index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.