14

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

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

我是否能够将额外的键:值对“推”到星期一的值?结果将是:

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

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

4

3 回答 3

43

做这样的事情

db.foo.update({"_id" :ObjectId("...") },{$set : {"Monday.z":8}})
于 2016-08-11T04:21:51.153 回答
2

如何向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"
    }
于 2021-01-30T17:33:37.550 回答
-8
var json = {
    Monday: { a:1, b:2 },
    Tuesday: { c:3, d:4 } }

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

console.log(json);
于 2016-08-11T04:17:15.953 回答