MongoDB:使用字典更新数组中的文档

编程入门 行业动态 更新时间:2024-10-24 00:30:07
本文介绍了MongoDB:使用字典更新数组中的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我发现了一个 StackOverflow 问题,非常接近回答我的问题,但不完全是这样.

I found a StackOverflow Question that comes very close to answering my question, but not quite there.

接受这个原始问题(修改数组中的文档),但假设您没有想要进行的特定更改.相反,我有一本我希望进行更改的字典.下面是一个例子:

Take this original question (modifying a document that is in an array) but assume that you do not have a specific change you wish to make. Instead, I have a dictionary of changes that I wish to make. Here is an example:

原始文档

{ _id: something, recipients: [{id:1, name:"Andrey", isread:false}, {id:2, name:"John", isread:false}] }

要进行的更改

{ isread: true, fullname: 'jonathan' }

如何将这本更改字典应用于 John (id:2)?如果它是相关的,我正在使用 MongoDB-Node.JS驱动谢谢

How can I apply this dictionary of changes to John (id:2)? Incase it is relevant, I am using the MongoDB-Node.JS Driver Thank you

推荐答案

就像在您引用的问题中一样,您需要使用 $ 位置运算符,但在这种情况下使用 update:

Just like in the question you referenced, you need to use the $ positional operator, but with update in this case:

collection.update({_id:something, 'recipients.id': 2}, {$set: {'recipients.$': { isread: true, fullname: 'jonathan' }}}, function (err) {...

编辑

要不替换整个数组元素对象,您必须执行以下操作:

To not replace the whole array element object you'd have to do something like this:

collection.update({_id:something, 'recipients.id': 2}, {$set: { 'recipients.$.isread': true, 'recipients.$.fullname': 'jonathan' }}, function (err) {...

更多推荐

MongoDB:使用字典更新数组中的文档

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

发布评论

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

>www.elefans.com

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