MongoDB:更新子文档 [英] MongoDB: Updating subdocument
本文介绍了MongoDB:更新子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个收藏集:
[{ "_id" : 7,
"category" : "Festival",
"comments" : [
{
"_id" : ObjectId("4da4e7d1590295d4eb81c0c7"),
"usr" : "Mila",
"txt" : "This is a comment",
"date" : "4/12/11"
}
]
}]
我只想在这样的注释中插入一个新字段:
All I want is to push insert a new field inside comments like this:
[{ "_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
}
]
}]
如何在注释子文档中插入
How can I insert inside the comments subdocument?
推荐答案
您需要使用 $位置运算符
例如:
update({
_id: 7,
"comments._id": ObjectId("4da4e7d1590295d4eb81c0c7")
},{
$set: {"comments.$.type": abc}
}, false, true
);
我没有测试它,但我希望它对您有帮助.
I didn't test it but i hope that it will be helpful for you.
如果要更改文档的结构,则需要使用
If you want to change the structure of document you need to use
db.collection.update(条件, objNew,upsert,multi)
db.collection.update( criteria, 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. 查看此详细信息
and insert new objNew with new structure. check this for more details
这篇关于MongoDB:更新子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文