How to add key-value pair to object in MongoDB
Asked Answered
R

4

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.

Ruthi answered 11/8, 2016 at 4:13 Comment(0)
C
47

Just do something like that

db.foo.update({"_id" :ObjectId("...") },{$set : {"Monday.z":8}})
Charwoman answered 11/8, 2016 at 4:21 Comment(0)
P
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
              },     
);

...
Pyrex answered 10/10, 2022 at 17:40 Comment(0)
I
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"
    }
Intellectuality answered 30/1, 2021 at 17:33 Comment(0)
B
-8
var json = {
    Monday: { a:1, b:2 },
    Tuesday: { c:3, d:4 } }

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

console.log(json);
Besiege answered 11/8, 2016 at 4:17 Comment(1)
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.Jackelinejackelyn

© 2022 - 2024 — McMap. All rights reserved.