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

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

问题描述

我有一个像这样的数据结构:
我们有一些centers. center有一些switches. 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更改为空".
当我知道端口的数组索引(此处数组索引为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天全站免登陆