Search code examples
mongodbmongodb-update

How to add key-value pair to object in MongoDB


If I have a document with the following basic structure:

{
  ...
  Monday: { a:1, b:2 },
  Tuesday: { c:3, d:4 }
  ...
}

Am I able to 'push' an additional key:value pair to Monday's value? Result would be:

{
  Monday: { a:1, b:2, z:8 },
  Tuesday: { c:3, d:4 }
  ...
}

The $push operator seems to only work for arrays.


Solution

  • Just do something like that

    db.foo.update({"_id" :ObjectId("...") },{$set : {"Monday.z":8}})