Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Update a field of an item in array with matching another field of that item

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"
                }
            ]
        }
     ]
  }

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.

like image 702
Aliaaa Avatar asked Sep 06 '25 04:09

Aliaaa


1 Answers

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

Update field in exact element array in MongoDB

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

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

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"
        }
    }
)
like image 163
Dmytro Shevchenko Avatar answered Sep 09 '25 20:09

Dmytro Shevchenko