Suppose I have different documents in different collections:
On cars:
{ "_id": 32534534, "color": "red", ... }
On houses:
{ "_id": 93867, "city": "Xanadu", ... }
How can I retrieve the corresponding document to the documents below, in people:
{ "name": "Alonso", "owns": [32534534], ... }
{ "name": "Kublai Khan", "owns": [93867], ... }
Can I use something like the code below?
(Note that I’m not specifying a catalog)
db.find({'_id': 93867})
If not, what would you suggest to achieve this efect?
I have just found this related question: MongoDB: cross-collection queries
Using DBrefs you can store links to documents outside your collection or even in another mongodb database. You will have to fetch the references in separate queries, different drivers handle this differently, for example with the python driver you can auto dereference.
An example of yours in the js shell might look like:
As you can see DBRefs are a formal spec for referencing objects, that always contain the
ObjectIdbut also can contain information on the database and the collection. In the above example you can see it stores the collectioncarsin the$reffield. Searching is trivial as you just do a query on the dbref:Dereferencing can be done via the
fetch()command in the shell:However depending on your use case you may want to optimise this and write some code that iterates over the
ownsarray and does as fewfind()queries as possible…