1

For the document matching the criteria _id equal to 100, the following operation update the value second element (array index of 1) in the tags field and the rating field in the first element (array index of 0) of the ratings array.

db.products.update(
   { _id: 100 },
   { $set:
      {
        "tags.1": "rain gear",
        "ratings.0.rating": 2
      }
   }
)

The above is a quote from the mongodb $set documentation, how would I go about adding a variable for the index so instead of "tags.1" it becomes "tags."+index

For example, if index is equal to 7 it would return the equivalent of "tags.7".

This is my code:

Users.findOneAndUpdate({'username': post.username}, { 
  $set: {
    "notifications.0": { 
      'id': post._id,  'message': post.message,  'amount': amount 
    } 
  } 
}, function () {})

It works perfectly but only because I hardcoded the 0 as the index. I want to replace that hardcoded 0 with an index variable.

5
  • What's wrong with replacing "notifications.0" with "notifications."+index ? Commented Apr 30, 2017 at 23:19
  • syntax error @Aaron Commented May 1, 2017 at 0:47
  • thanks @JohnyHK that question led me to my answer! since i dont think its an exact dupe ill post my answer. Commented May 1, 2017 at 0:50
  • maybe it is a dupe :/ should i delete it? Commented May 1, 2017 at 0:59
  • It's the same basic issue so I did mark it as a dupe. No need to delete though. Commented May 1, 2017 at 13:06

1 Answer 1

0

Build up the query like so

var key = "notifications."+index;
var obj = {};
obj[key] = { 'id': post._id, 'message': post.message, 'amount': amount };
Users.findOneAndUpdate({'username': post.username}, { $set: obj }, function () {}
Sign up to request clarification or add additional context in comments.

Comments