18

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.

DAXaholic
  • 33,312
  • 6
  • 76
  • 74
flimflam57
  • 1,334
  • 4
  • 16
  • 31

4 Answers4

47

Just do something like that

db.foo.update({"_id" :ObjectId("...") },{$set : {"Monday.z":8}})
DAXaholic
  • 33,312
  • 6
  • 76
  • 74
3

I know this might be irrelevant to the question but as a matter of fact, I opened this page because I was looking for an exact query with mongoose. here is my answer with mongoose.

If we have an abstract model (mongoose schema) named week in our javascript application then the code will be:

// javascript with mongoose

...

const key = "z";

const KeyValue = 8;

await week.updateOne({
                _id,           // mongoDb document id
              },
              {
                $set:{
                       [`Monday.${key}`]: KeyValue,
                     },
              },
              {
                upsert: true   // options
              },     
);

...
mmRoshani
  • 99
  • 7
2

How to add a new key:value pair to all existing objects of a mongoDB documents

Old Key and Value Pairs

> db.students.find().pretty();
 { "_id" : ObjectId("601594f5a22527655335415c"), "name" : "Doddanna" }                                                                                                  
 { "_id" : ObjectId("601594f5a22527655335415d"), "name" : "Chawan" }

Update New Key and Value Pairs Using updateMany() and $set

> db.students.updateMany({},{$set:{newKey1:"newValue1", newKey2:"newValue2", newKeyN:"newValueN"}});
 { "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }

Have a look on Updated pretty result

> db.students.find().pretty();
  {
    "_id" : ObjectId("601594f5a22527655335415c"),
    "name" : "Doddanna",
    "newKey1" : "newValue1",
    "newKey2" : "newValue2",
    "newKeyN" : "newValueN"
   }
   {
    "_id" : ObjectId("601594f5a22527655335415d"),
    "name" : "Chawan",
    "newKey1" : "newValue1",
    "newKey2" : "newValue2",
    "newKeyN" : "newValueN"
    }
Doddanna D
  • 31
  • 4
-8
var json = {
    Monday: { a:1, b:2 },
    Tuesday: { c:3, d:4 } }

json['Monday']['z'] = 8;

console.log(json);
Vince Bowdren
  • 8,326
  • 3
  • 31
  • 56
Meena
  • 97
  • 2
  • 3
    This answer doesn't address the question, regarding the operation in MongoDB. The document in the question refers to a document(similar to a row) in MongoDB. – Mina May 08 '17 at 18:17