0

I have a document like this:

{
   _id : ...,
   key : { 
        a : 1,
        b : 2,
        c : 3
   }
}

And I will update this collection with this:

var data = {
    b : 4,
    c : 5
};

And I want my document be update to this:

{
   _id : ...,
   xxx : { 
        a : 1,
        b : 4,
        c : 5
   }
}

So if I do this:

db.myColl.update(  _id , { $set: {"xxx": data } );

it will end up a document like this:

{
   _id : ...,
   xxx: { 
      b : 4,
      c : 5
   }
}

So I have to do it twice:

db.myColl.update(  _id , { $set: {"xxx.b": data.b } );
db.myColl.update(  _id , { $set: {"xxx.c": data.c } );

Is it possible to do it in single command?

1
  • No, thats the only way I have seen. $set replaces any sub properties with the new values, so if its missing one, it considers that deleted. Commented May 20, 2015 at 23:49

1 Answer 1

1

You can do this by combining both of the $set terms into a single update:

db.myColl.update(_id, { $set: {"xxx.b": data.b, "xxx.c": data.c } });
Sign up to request clarification or add additional context in comments.

1 Comment

... I would even say this should be done that way -- so the update is atomic. When the OP uses two separate updates, there is a possibility for concurrent reads on the DB to see a a partially updated document.

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.