MongoDB:更新子文档

编程入门 行业动态 更新时间:2024-10-17 07:37:19
本文介绍了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:更新子文档

本文发布于:2023-11-22 13:38:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617631.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!