8

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

If yes, how?

If no, why not?

Community
  • 1
  • 1
sssilver
  • 2,549
  • 3
  • 24
  • 34

2 Answers2

10

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

Eve Freeman
  • 32,467
  • 4
  • 86
  • 101
1

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

It includes time, machine id, process id and a random number. However, it does not include database or collection name. Therefore, it is impossible to fetch a document using only the id. You have to provide database and collection names as well.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • 1
    But I'm not interested in the collection -- I'm interested in the object itself! In other words, I don't mind not knowing which collection the fetched object belongs to. Does this mean that there is no one single list of all the objects in the database? – sssilver Mar 15 '12 at 21:23
  • 1
    There never will be such a list either. An ObjectId is globally unique, but you don't have to use one for the document id. You can use pretty much any string you want and only have it be unique within the collection. Because of that, there's no way for Mongo to determine a collection from the id. – Tim Gautier Mar 15 '12 at 22:16