MongoDB: Find an object by its ID without knowing the collection

user41951 picture user41951 · Mar 7, 2017 · Viewed 9.9k times · Source

I have an mongodb databse with 100+ collections. I'm trying to find an object, with a known ObjectID, that belongs to some (unknown) collection of this database.

I tried to do:

db.getCollectionNames().forEach(function(collname) {
    var object = db[collname].find({'_id' : ObjectId("54d0232ef83ea4000d2c0610")});
    if(object._id !== undefined){
        printjson("Found in " >> collname);
    }
});

... similar to what's suggested here: Loop through all Mongo collections and execute query

However, I am getting no results from the script.

Edit:

When I do this I get the expected Found!:

var object = db['rightcollection'].findOne({'_id' : ObjectId("54d0232ef83ea4000d2c0610")});
if(object !== null){
    printjson("Found!");
}

But the following returns 0 (instead of returning nothing as in the original example):

db.getCollectionNames().forEach(function(collname) {
    var object = db[collname].findOne({'_id' : ObjectId("54d0232ef83ea4000d2c0610")});
    if(object !== null){
        printjson("Found in " >> collname);
    }
});

Answer

Miguel Luisillo picture Miguel Luisillo · Jul 31, 2017

try this:

db.getCollectionNames().forEach(function(collName) {
  var doc = db.getCollection(collName).findOne({"_id" : "54d0232ef83ea4000d2c0610"});
  if(doc != null) print(doc._id + " was found in " + collName); 
});  

using db.getCollection

Edit: you can get more detailed info on this question: Get a document in MongoDB without specifying collection