0

How to update the value of shopping and food for particular array element in mongo db ?

MongoDB Document :

   {
    "data": [
        {
            "_id": "5e131eb4ea0c191cdc06f96b",
            "firstName": "Anirudh",
            "lastName": "Singla",
            "gender": "Male",
            "username": "anirudhsingla8",
            "email": "anirudhsingla8@gmail.com",
            "password": "rj13sl1608",
            "cards": [
                {
                    "card_number": "1014220122322233",
                    "shopping": 0,
                    "food": 0
                },
                {
                    "card_number": "1014220122322234",
                    "shopping": 0,
                    "food": 0
                }
           }
         ]
}

I was trying to update the value in subelement of array like the current value of shopping for "card_number"="1014220122322234" is 0. but I want to update it according to user need.like if user enter 10 then it should be updated to 0+10=10, if it is 10 and user enter 16 then it should be updated to 10+16=26 like this. But I am not able to figure out query for this type of update on mongodb docs.

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
  • Since `cards` are nested documents, you need to read the document from the db first, make the necessary changes in memory and save it back. Another option is using [partial update](https://stackoverflow.com/a/16119136/210085). – Andy Jan 12 '20 at 04:51
  • Does this answer your question? [MongoDB - Update objects in a document's array (nested updating)](https://stackoverflow.com/questions/10522347/mongodb-update-objects-in-a-documents-array-nested-updating) – whoami - fakeFaceTrueSoul Jan 12 '20 at 04:53

1 Answers1

0

You can use the positional($) operator.

User.update(
  {
    _id: userId,
    'cards.card_number': '1014220122322233'
  },
  {
    $inc: { 'cards.$.shopping': 1, 'cards.$.food': 1 }
  }
);

This would increment both shopping, food by 1.

Sihoon Kim
  • 1,481
  • 2
  • 13
  • 32