mongo-shellstudio3t

How to iterate queries in mongo shell


Surely, this is simple. I cannot figure this out. In Mongo shell I have the following command:

db.getCollection("CollectionName")
        .findAndModify({query: {"Property.0.Element": {"$type" : 1}},
                        update: {$set: {"Property.0.Element":""}}
                      })

If I run this command several times, eventually it returns null and I know that I have changed all of the fields that I wanted to change. If however I run:

for(j = 0; j < 50;j++) {      
    var loc = "Property."+j+".Element";
    db.getCollection("ShelbyCoAssessorDeepStaging")
        .findAndModify({query: {loc : {"$type" : 1}},
                        update: {$set: {loc:""}}
                      })
}

Then I have null returned, but none of the values actually changed. Why is this? Note: I am running this in studio3T's intellishell against an atlas cluster at version 3.6.6.


Solution

  • You are trying to use dynamic keys for a query object. But JavaScript does not support this approach in object literals. Please consider the following example on the MongoDB shell or Studio 3T's IntelliShell:

    > var fieldName = "foo"
    > var query = { fieldName: 1 }
    > printjsononeline(query)
    {  "fieldName" : 1 }
    

    In this small example, we create a variable that contains the name of the key that we want to set inside a query object. But JavaScript does not expect a variable as a key inside an object literal. The symbol is directly used as key name, it absolutely does not matter if the key is quoted or not.

    If you want to have dynamic key names in JavaScript, you can use the simple bracket notation (or "member index access"):

    > var fieldName = "foo"
    > var query = {}
    > query[fieldName] = 1
    1
    > printjsononeline(query)
    {  "foo" : 1 }
    

    If we apply this to your example, we get the following code to be run on the MongoDB shell or Studio 3T IntelliShell:

    for(j = 0; j < 50;j++) {      
        var loc = "Property."+j+".Element";
     var theQuery = {};
     theQuery[loc] = {"$type" : 1};
     var theUpdate = {$set: {}};
     theUpdate["$set"][loc] = "";
        db.getCollection("ShelbyCoAssessorDeepStaging")
            .findAndModify({query: theQuery,
                            update: theUpdate
                          })
    }