Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a document in MongoDB without specifying collection

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?

like image 301
sssilver Avatar asked Mar 15 '12 21:03

sssilver


People also ask

How do I get documents from MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.

How do I capture a single record in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

Is a MongoDB method to retrieve documents from a collection?

find() is a function that retrieves documents from a MongoDB database. In MongoDB, the find method is used to retrieve a specific document from the MongoDB collection.

How do I reference a document in MongoDB?

MongoDB applications use one of two methods to relate documents: Manual references save the _id field of one document in another document as a reference. Your application runs a second query to return the related data. These references are simple and sufficient for most use cases.

What is the difference between a document and a collection in MongoDB?

A collection holds one or more BSON documents. Documents are analogous to records or rows in a relational database table. Each document has one or more fields; fields are similar to the columns in a relational database table.


1 Answers

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

like image 105
Eve Freeman Avatar answered Oct 27 '22 11:10

Eve Freeman