MongoDb: How to disable attribute from nested arrays?

I am trying to remove an attribute from a triple nested array without success. The following is an example of the data I want to delete:

Controls: [
    {    
        Name: 'ControlNumberOne',
        Submit: {   
            Executes: [
                {
                    Name: 'execute',
                    Type: 0
                },
                {
                    Name: 'anotherExecute',
                    Type: 0
                }
            ]
        }
    },
    {    
        Name: 'ControlNumberTwo',
        Submit: {   
            Executes: [
                {
                    Name: 'anotherFromAnotherControl',
                    Type: 1
                }
            ]
        }
    }

]

I tried the following update requests, but none of them worked:

  • db.Page.update('Controls.Submit.Executes.Type': { $exists : true } }, { $unset : { 'Controls.Submit.Executes.Type' : 1 } }, false, true);)

  • db.Page.update('Controls.Submit.Executes.Type': { $exists : true } }, { $unset : { 'Controls.$.Submit.Executes.$.Type' : 1 } }, false, true);)

However, if I execute db.Page.find('Controls.Submit.Executes.Type': { $exists : true } }), it returns all Executes that still have the Type attribute.

Can this be achieved? Thank!

+5
source share
2 answers

Requesting and updating nested arrays is not supported (yet) directly by MongoDB commands, this should be done on the client side:

  • read the document in a variable
  • manipulate an array
  • refresh document, rewrite entire array

Jira: https://jira.mongodb.org/browse/SERVER-831 stackoverflow: Mongo

, :

db.xx.find(
    {'Controls.Submit.Executes.Type': { $exists : true } }
).forEach( function(doc) {
    doc.Controls.forEach( function(c) {
        c.Submit.Executes.forEach( function(e) {
            if ( e.Type != undefined ) delete e.Type;        
        });
    });
    db.xx.update({_id: doc._id},{$set:{Controls:doc.Controls}});
});

:

> db.xx.findOne()
{
    "Controls" : [
        {
            "Name" : "ControlNumberOne",
            "Submit" : {
                "Executes" : [
                    {
                        "Name" : "execute"
                    },
                    {
                        "Name" : "anotherExecute"
                    }
                ]
            }
        },
        {
            "Name" : "ControlNumberTwo",
            "Submit" : {
                "Executes" : [
                    {
                        "Name" : "anotherFromAnotherControl"
                    }
                ]
            }
        }
    ],
    "_id" : ObjectId("5159ff312ee0f7d445b03f32")
}
+5

- ( ), .

MongoDB 3. 6+ , . .:

db.getCollection('xxx').update(
   {'Controls.Submit.Executes.Type': { $exists : true },
   { $unset : {'Controls.$[].Submit.Executes.$[].Type' : 1}}
)

CLI MongoDB, RoboMongo Mongo-Java.

0

All Articles