Search code examples
node.jsmongodbmongodb-queryincrementsubdocument

Increment nested field value in mongodb if exists or create nested fields


I need to increment the multi level nested field value if it exists or create the complete nested field Object structure.

Structure of my document

Doc1 {
_id:ObjectId(),
myField: {
  nested:{
      x: 5,
      y: 10,
      z: 20
  }
 }
}

Goal Explanation: I need a way to write a single query:

  • If myField exists: Increment the value of my nested field myField.nested.x by 10.
  • If myField does not exists: Create the below field with initial values same as given in the Doc1.

Attempt and explanation:

 db.collection('collectionName').findOneAndUpdate(
    {_id:"userId","myField" : { $exists : true }},
    {$inc:{'myField.nested.x':10}
 })

This way, I can increment the nested field if it exists but in case of non existence I cannot set myField as same as Doc1.

Although, I can use another query after response in my NodeJs callback to achieve my required behaviour. But I need some elegant solution in a single query.

I am using MongoDB version 4.0.4, Thanks in Advance.


Solution

  • Try this query

    If the field does not exist, $inc creates the field and sets the field to the specified value.

    db.collection('collectionName').findOneAndUpdate({_id:"userId"},
    {$inc:{'myField.nested.x':10}
    })