如何在MongoDB中向对象添加键值对

时间:2016-08-11 04:13:35

标签: mongodb mongodb-update

如果我的文档具有以下基本结构:

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

我是否能够推动'一个额外的关键:价值对周一的价值?结果将是:

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

$push运算符似乎只适用于数组。

3 个答案:

答案 0 :(得分:20)

做这样的事

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

答案 1 :(得分:2)

如何添加一个新的key:value到一个mongoDB文档的所有现有对象

旧的键值对

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

使用 updateMany() 和 $set 更新新的键值对

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

看看更新的漂亮结果

> 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"
    }
<块引用>

答案 2 :(得分:-6)

var json = {
    Monday: { a:1, b:2 },
    Tuesday: { c:3, d:4 } }

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

console.log(json);