How to add key-value pair to object in MongoDB

flimflam57 picture flimflam57 · Aug 11, 2016 · Viewed 22k times · Source

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.

Answer

DAXaholic picture DAXaholic · Aug 11, 2016

Just do something like that

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