Question

I was wondering if it was possible to update the embedded embedded value of an attribute (with two deep levels) please?

For example, if I have the following document :

{
    _id: ObjectId("5372523e4f611ef8255c5735"),

    places: [
        {
            idPlace: 2,
            namePlace: "Name of the place 2",
            typePlace: "Type of the place 2"
            },
            screens: [
                {
                    idScreen: 1,
                    nameScreen: "Name 1 of the screen",
                    statusScreen: false
                },
                {
                    idScreen: 2,
                    nameScreen: "Name 2 of the screen",
                    statusScreen: false
                },
                {
                    idScreen: 3,
                    nameScreen: "Name 3 of the screen",
                    statusScreen: false
                }
        },
        {
            idPlace: 3,
            namePlace: "Name of the place 3",
            typePlace: "Type of the place 3"
            },
            screens: [
                {
                    idScreen: 5,
                    nameScreen: "Name 5 of the screen",
                    statusScreen: false
                },
                {
                    idScreen: 6,
                    nameScreen: "Name 6 of the screen",
                    statusScreen: false
                },
                {
                    idScreen: 7,
                    nameScreen: "Name 7 of the screen",
                    statusScreen: false
                }
        }
    ]
}

And I wanted to modify the value of the attribute 'statusScreen' of the 'idScreen': 5 to true. So I tried the following command (according to the post Updating embedded document property in Mongodb):

db.mycollection.update(  {'places.screens': {$elemMatch: {'idScreen': 5} }},  { $set: { "online": true }},   { multi: true } );

but this creates me an attribute 'online': true in the root of my document and don't modify the value of my desired attribute.

Have you any idea of what is wrong please ?

Best Loic

Was it helpful?

Solution

In theory you should you positional operator $ to match specific item and update it. But the issue is you need to use two positional operators $ to match position in places and to match position in screens. Unfortunately usage of two positional operators is not yet supported, see there https://jira.mongodb.org/browse/SERVER-831.

So you are unable to update doc in one query.

However you could find all necessary documents by using {'places.screens.idScreen': 5} } query and then update document based on known positions in arrays.

Edit: code to update specific elements in arrays

db.coll.update(
   {'places.screens.idScreen': 5},
   {$set:{"places.0.screens.0.statusScreen":true}} 
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top