Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - manual references example

Tags:

mongodb

I was reading the manual references part from the MongoDB Database References documentation, but I don't really understand the part of the "second query to resolve the referenced fields". Could you give me an example of this query, so i can get a better idea of what they are talking about.

"Manual references refers to the practice of including one document’s _id field in another document. The application can then issue a second query to resolve the referenced fields as needed."

like image 597
Javier Cárdenas Avatar asked Feb 06 '14 01:02

Javier Cárdenas


1 Answers

The documentation is pretty clear in the manual section you are referring to which is the section on Database References. The most important part in comprehending this is contained in the opening statement on the page:

"MongoDB does not support joins. In MongoDB some data is denormalized, or stored with related data in documents to remove the need for joins. However, in some cases it makes sense to store related information in separate documents, typically in different collections or databases."

The further information covers the topic of how you might choose to deal with accessing data that you store in another collection.

There is the DBRef specification which without going into too much more detail, may be implemented in some drivers as a way that when these are found in your documents they will automatically retrieve (expand) the referenced document into the current document. This would be implemented "behind the scenes" with another query to that collection for the document of that _id.

In the case of Manual References this is basically saying that there is merely a field in your document that has as it's content the ObjectId from another document. This only differs from the DBRef as something that will never be processed by a base driver implementation is leaves how you handle any further retrieval of that other document soley up to you.

In the case of:

> db.collection.findOne()

{
   _id: <ObjectId>,
   name: "This",
   something: "Else",
   ref: <AnotherObjectId>
}

The ref field in the document is nothing more than a plain ObjectId and does nothing special. What this allows you to do is submit your own query to get the Object details this refers to:

> db.othercollection.findOne({ _id: <AnotherObjectId > })
{
  _id: <ObjectId>
  name: "That"
  something: "I am a sub-document to This!"
}

Keep in mind that all of this processes on the client side via the driver API. None of this fetching other documents happens on the server in any case.

like image 131
Neil Lunn Avatar answered Oct 16 '22 02:10

Neil Lunn