MongoDB:更新数组中项目的一个字段,并匹配该项目的另一个字段 [英] MongoDB: Update a field of an item in array with matching another field of that item

查看:27
本文介绍了MongoDB:更新数组中项目的一个字段,并匹配该项目的另一个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据结构:
我们有一些中心.center 有一些 switchs.switch 有一些 ports.

I have a data structure like this:
We have some centers. A center has some switches. A switch has some ports.

    {
     "_id" : ObjectId("561ad881755a021904c00fb5"),
     "Name" : "center1",
     "Switches" : [
        {
            "Ports" : [
                {
                    "PortNumber" : 2,
                    "Status" : "Empty"
                },
                {
                    "PortNumber" : 5,
                    "Status" : "Used"
                },
                {
                    "PortNumber" : 7,
                    "Status" : "Used"
                }
            ]
        }
     ]
  }

我只想编写一个更新查询来将 PortNumber 为 5 的端口的 Status 更改为Empty".
当我知道端口的数组索引(这里数组索引为 1)时,我可以更新它:

All I want is to write an Update query to change the Status of the port that it's PortNumber is 5 to "Empty".
I can update it when I know the array index of the port (here array index is 1) with this query:

db.colection.update(
    // query
    {
        _id: ObjectId("561ad881755a021904c00fb5")
    },
    // update 
    {
        $set : { "Switches.0.Ports.1.Status" : "Empty" }
    }
);

但我不知道那个端口的数组索引.
感谢您的帮助.

But I don't know the array index of that Port.
Thanks for help.

推荐答案

您通常会使用位置运算符 $ 来执行此操作,如此问题的答案中所述:

You would normally do this using the positional operator $, as described in the answer to this question:

更新 MongoDB 中精确元素数组中的字段

不幸的是,目前位置运算符仅支持一个数组级别的匹配深度.

Unfortunately, right now the positional operator only supports one array level deep of matching.

对于您想要的那种行为,有一张 JIRA 票证:https://jira.mongodb.org/browse/SERVER-831

There is a JIRA ticket for the sort of behavior that you want: https://jira.mongodb.org/browse/SERVER-831

如果你可以将 Switches 变成一个对象,你可以这样做:

In case you can make Switches into an object instead, you could do something like this:

db.colection.update(
    {
        _id: ObjectId("561ad881755a021904c00fb5"),
        "Switch.Ports.PortNumber": 5
    }, 
    {
        $set: {
            "Switch.Ports.$.Status": "Empty"
        }
    }
)

这篇关于MongoDB:更新数组中项目的一个字段,并匹配该项目的另一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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