如何将键值对添加到 MongoDB 中的对象
How to add key-value pair to object in MongoDB
如果我有一个具有以下基本结构的文档:
{
...
Monday: { a:1, b:2 },
Tuesday: { c:3, d:4 }
...
}
我可以 'push' 额外 key:value 一对到周一的价格吗?结果将是:
{
Monday: { a:1, b:2, z:8 },
Tuesday: { c:3, d:4 }
...
}
$push
运算符似乎只适用于数组。
var json = {
Monday: { a:1, b:2 },
Tuesday: { c:3, d:4 } }
json['Monday']['z'] = 8;
console.log(json);
就这样吧
db.foo.update({"_id" :ObjectId("...") },{$set : {"Monday.z":8}})
如何将新的key:value对添加到[=35的所有现有对象=] 文档
旧键值对
> 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"
}
如果我有一个具有以下基本结构的文档:
{
...
Monday: { a:1, b:2 },
Tuesday: { c:3, d:4 }
...
}
我可以 'push' 额外 key:value 一对到周一的价格吗?结果将是:
{
Monday: { a:1, b:2, z:8 },
Tuesday: { c:3, d:4 }
...
}
$push
运算符似乎只适用于数组。
var json = {
Monday: { a:1, b:2 },
Tuesday: { c:3, d:4 } }
json['Monday']['z'] = 8;
console.log(json);
就这样吧
db.foo.update({"_id" :ObjectId("...") },{$set : {"Monday.z":8}})
如何将新的key:value对添加到[=35的所有现有对象=] 文档
旧键值对
> 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"
}