Get a document in MongoDB without specifying collection

Yes, but not in a scalable way (since you must query each collection). If you have 2 or 3 collections, this might be ok, but… you probably should review your design to figure out why you’re doing this. Why are you, by the way?

  1. You get a list of all of the collections in the database.
  2. You loop through them, and query based on _id

Sample shell code:

db.test1.save({});
db.test2.save({});  
db.test3.save({});
db.test4.save({});
db.test5.save({}); 
db.test6.save({});

db.test2.findOne(); // gives: { "_id" : ObjectId("4f62635623809b75e6b8853c") }

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

gives: 4f62635623809b75e6b8853c was found in test2

Leave a Comment