3

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.

1
  • 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} }) Commented Oct 21, 2019 at 16:48

1 Answer 1

0

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}
})
Sign up to request clarification or add additional context in comments.

1 Comment

How does this work with dates? If I want to add 6 months to a date, but if the date doesn't exist, choose $$NOW as the date?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.