Sunday, 30 April 2017

Using $set with an index variable to update a document

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.



via Leathan Axe

No comments:

Post a Comment