如何在 mongodb 中更新多个数组元素 [英] How to Update Multiple Array Elements in mongodb

查看:49
本文介绍了如何在 mongodb 中更新多个数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含元素数组的 Mongo 文档.

I have a Mongo document which holds an array of elements.

我想重置数组中所有对象的 .handled 属性,其中 .profile = XX.

I'd like to reset the .handled attribute of all objects in the array where .profile = XX.

文档格式如下:

{
    "_id": ObjectId("4d2d8deff4e6c1d71fc29a07"),
    "user_id": "714638ba-2e08-2168-2b99-00002f3d43c0",
    "events": [{
            "handled": 1,
            "profile": 10,
            "data": "....."
        } {
            "handled": 1,
            "profile": 10,
            "data": "....."
        } {
            "handled": 1,
            "profile": 20,
            "data": "....."
        }
        ...
    ]
}

所以,我尝试了以下方法:

so, I tried the following:

.update({"events.profile":10},{$set:{"events.$.handled":0}},false,true)

但是它只更新每个文档中第一个匹配的数组元素.(这是 $ - 位置运算符 的定义行为.)

However it updates only the first matched array element in each document. (That's the defined behaviour for $ - the positional operator.)

如何更新所有匹配的数组元素?

How can I update all matched array elements?

推荐答案

更新:从 Mongo 3.6 版开始,此答案不再有效,因为提到的问题已修复,并且有多种方法可以实现.请检查其他答案.

目前无法使用位置运算符来更新数组中的所有项目.参见 JIRA http://jira.mongodb.org/browse/SERVER-1243

At this moment it is not possible to use the positional operator to update all items in an array. See JIRA http://jira.mongodb.org/browse/SERVER-1243

作为一种解决方法,您可以:

As a work around you can:

  • 单独更新每个项目(events.0.handled events.1.handled...) 或...
  • 阅读文档,进行编辑手动并保存它替换较旧的(检查 如果更新Current" 如果你想确保原子更新)
  • Update each item individually (events.0.handled events.1.handled ...) or...
  • Read the document, do the edits manually and save it replacing the older one (check "Update if Current" if you want to ensure atomic updates)

这篇关于如何在 mongodb 中更新多个数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆