MongoDB:更新子文档
我有这个收藏:MongoDB:更新子文档,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"
}
]
}]
我只想在注释中插入一个新字段,如下所示:
[{ "_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
}
]
}]
如何在注释子文档中插入?您需要使用
例如:
update({
_id: 7,
"comments._id": ObjectId("4da4e7d1590295d4eb81c0c7")
},{
$set: {"comments.$.type": abc}
}, false, true
);
我没有测试它,但我希望它会对你有所帮助
如果要更改文档的结构,则需要使用
db.collection.update(标准,
objNew、upsert、multi)
论据:
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 只有在“comments”字段不是数组的情况下,$positional运算符才能按预期工作。OP的json格式不正确,但看起来可能是数组 问题是mongodb现在只更新与查询匹配的数组的第一个元素。尽管有一个RFE可用于添加对更新所有匹配数组元素的支持:
要解决数组的这个问题,您只需定期查找,然后分别更新数组中的元素。这对我不适用。它只更新数组中的一项,而不是全部。尽管我通过了多项测试,但对我来说也不起作用。如果我设置了new_comments.type,它可以工作,但是当我尝试修改现有的类似父级的注释时,它不工作。请注意,由于更新的MongoDB 2.2版语法是db.collection.update(,{upsert:,multi:})文档似乎已更改。这涉及到位置: