【发布时间】:2014-03-23 07:35:19
【问题描述】:
我刚刚开始使用 MongoDB。我有一个这样的文件:
{
"_id": "12345"
"body": "Here is the body"
"comments":[
{
"name": "Person 1"
"comm": "My comment"},
{
"name": "Person 2"
"comm": "Comment 2"}
]
"author":"Author 1"
}
我想把这个文件改成:
{
"_id": "12345"
"body": "Here is the body"
"comments":[
{
"name": "Person 1"
"comm": "My comment"
"checks_": 1
},
{
"name": "Person 2"
"comm": "Comment 2"
"checks_": 4
}
]
"author": "Author 1"
}
我试过了:
db.coll.update({ "_id":12345},{ "$set":{ "comments" :{ "checks_": 1}}})
这会删除 cmets 中的所有子文档并添加 {checks_:1} 到其中。
我哪里错了?
【问题讨论】:
-
找不到对我有帮助的解决方案..
-
如果要更新单个数组子文档,可以执行 db.coll.update({id:12345},{$set:{"cmets.0.checks “:1}})。这将更新数组索引 0 处的文档。
-
啊,谢谢,成功了!
-
如果我需要一次性完成所有子数组怎么办?
标签: mongodb mongo-shell