Get a document in MongoDB without specifying a collection

MongoDB identifiers are unique to a single database cluster. Is it possible to get documents using their identifiers without specifying a collection name?

If so, how?

If not, why not?

+6
source share
2 answers

Yes, but not in a scalable way (since you have to query each collection). If you have 2 or 3 collections, this might be fine, but ... you probably should look at your design to understand why you are doing this. Why are you, by the way?

  • You get a list of all the collections in the database.
  • You browse them and request based on _id

Shell code example:

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

+7
source

ObjectId is designed to be globally unique (worldwide, and not just within a single cluster). And that is pretty much the case.

It includes time, machine ID, process ID, and random number. However, it does not include the name of the database or collection. Therefore, it is not possible to retrieve a document using only the identifier. You must also provide database names and collections.

+2
source

Source: https://habr.com/ru/post/910849/


All Articles