Home > Mobile >  Mongodb: Loop through all database and collection to find a field ( key ) in used?
Mongodb: Loop through all database and collection to find a field ( key ) in used?

Time:09-23

I have set of databases in mongo and each has set of collections. I need to iterate through all the databases and collections to find whether key being used in any collections. With googling i have mange to iterate through databases and collections. But I'm unable to find if certain key is used in any collection. Following is my script execute in mongodb shell.

db = db.getSiblingDB("admin");
var dbs = db.runCommand({ "listDatabases": 1 }).databases;
dbs.forEach(function(database) {
  db = db.getSiblingDB(database.name);
  cols = db.getCollectionNames();
  cols.forEach(function(col) {
    db[col].find({}).forEach(function(field) {
        //print(field);
        if( field == "testKey"){
            print(col   " has column")
        }
    });
    
});

});

How can I correct this script if the filed is equals to "testKey" then print that database and collection. Currently this does not go inside to if condition even-though i have "testKey" in some collections.

CodePudding user response:

Note that find returns list of documents so actually you need another iteration on the keys of that document.

db = db.getSiblingDB("admin");
var dbs = db.runCommand({ "listDatabases": 1 }).databases;
dbs.forEach(function (database) {
    db = db.getSiblingDB(database.name);
    cols = db.getCollectionNames();
    cols.forEach(col =>
        db[col].find({}).forEach(doc =>
            Object.keys(doc).forEach(key => {
                print(key === 'testKey')
            })
        )
    )
});
  • Related