Home > Blockchain >  How to perform addition in already existing json object in mongoDB?
How to perform addition in already existing json object in mongoDB?

Time:09-16

I want to add the cost of a particular month for a specific category. This is my object stored in MongoDB :

{
  "2022":{
        "January":{
              "Food":30,
              "Traveling":0,
              "Medical":0,   
         },
         "Feburary":{
              "Food":1000,
              "Traveling":0,
              "Medical":50,   
         },
         "March":{
              "Food":100,
              "Traveling":20,
              "Medical":10,   
         }
    }
}

Now, I am making a patch request:

{
   "month":"March",
   "monthData":[70,45,100]
}

Now, I want my data to be updated like this:

{
    "2022":{
         "January":{
             "Food":30,
             "Traveling":0,
             "Medical":0,
        },
         "Feburary":{
             "Food":1000,
             "Traveling":0,
             "Medical":50,
        },
         "March":{
             "Food":170,
             "Traveling":65,
             "Medical":110,
       }
   }
}

What query should I write using Model.findAndUpate(filter,object) so that above thing works.

CodePudding user response:

Your patch request looks to me like this:

db.collection.update({},
{
 "$inc": {
    "2022.March.Food": 70,
    "2022.March.Traveling": 45,
    "2022.March.Medical": 100
  }
})

Playgroud

CodePudding user response:

You can use a concept of Aggregation pipeline in MongoDB.

Check this for your reference

But this is easier to do with Node.js or whatever the backed language you are using.

  • Related