的MongoDB:更新子文档
问题描述:
我有这样的集合:的MongoDB:更新子文档
[{ "_id" : 7,
"category" : "Festival",
"comments" : [
{
"_id" : ObjectId("4da4e7d1590295d4eb81c0c7"),
"usr" : "Mila",
"txt" : "This is a comment",
"date" : "4/12/11"
}
]
}]
所有我想要的是插入推一个新的领域内的评论是这样的:
[{ "_id" : 7,
"category" : "Festival",
"comments" : [
{
"_id" : ObjectId("4da4e7d1590295d4eb81c0c7"),
"usr" : "Mila",
"txt" : "This is a comment",
"date" : "4/12/11",
"type": "abc" // find the parent doc with id=7 & insert this inside comments
}
]
}]
我怎样才能插入注释子文档里面?
答
您需要使用the $ positional operator
例如:
update({
_id: 7,
"comments._id": ObjectId("4da4e7d1590295d4eb81c0c7")
},{
$set: {"comments.$.type": abc}
}, false, true
);
我没有测试,但我希望它能对你有所帮助。
如果你想改变的文件,你需要使用
db.collection.update结构(标准, objNew,UPSERT,多)
参数:
criteria - query which selects the record to update; objNew - updated object or $ operators (e.g., $inc) which manipulate the object upsert - if this should be an "upsert"; that is, if the record does not exist, nsert it multi - if all documents matching criteria should be updated
并插入新的结构新objNew。 check this for more details
答
如果'comments'字段不是数组,那么$ positions操作符只会按预期工作。 OP的json格式不正确,但它看起来可能是一个数组。
现在的问题是,mongodb现在只会更新匹配查询的数组的第一个元素。虽然有一个RFE打开以添加对更新所有匹配阵列元素的支持:https://jira.mongodb.org/browse/SERVER-1243
要解决数组中的此问题,您只需执行常规查找,然后分别更新数组中的元素。
不起作用。该字段可能不存在 – kheya 2011-04-13 09:29:53
我得到它的工作。 thx – kheya 2011-04-13 17:18:01
这不为我工作。它只是更新数组中的一个项目,而不是全部。即使我通过了多个 – 2012-09-30 22:35:14