I am looking for some information about joins and how they behave within MongoDB
. While I appreciate that a large amount of the power behind a NoSQL database is to store all information in document, and that document to contain as much information as possible so that you don't have to do multiple queries
However I also appreciate that there are some scenarios where you may want to minimise the duplication of data so that you minimise the risk of consistency issues.
When using document references, is there any way to return a single document? I have tried the $lookup
function, and while it does return me the right result, it returns one document for every array entry.
Assuming the following structure:
Customer:
{
_id: ObjectId("578d706916f07969c4b0cad1"),
name: "fred",
orders: [ObjectId("578d706916f07969c4b0cad2"),ObjectId("578d706916f07969c4b0cad3")]
}
Orders:
{
_id: ObjectId("578d706916f07969c4b0cad2"),
date: xxxx,
items: [a,b,c,d]
},
{
_id: ObjectId("578d706916f07969c4b0cad2"),
date: xxxx,
items: [x,y,z]
}
Using lookup, I can get a result of 2 documents, one for each order with the customer data appended, however I am looking for a single document with an array or order information - an embedded document
. i.e. the following structure
{
_id: ObjectId("578d706916f07969c4b0cad1"),
name: "fred",
orders: [
{
_id: ObjectId("578d706916f07969c4b0cad2"),
date: xxxx,
items: [a,b,c,d]
},
{
_id: ObjectId("578d706916f07969c4b0cad2"),
date: xxxx,
items: [x,y,z]
}]
}
Is this possible within MongoDB
? Or is the join
process so closely matched to SQL databases that you will always return the duplicated customer information when trying to join data? I know that the data could be turned into a single document within an application such as node
however is it possible, from the way the query is written, to return it pre-formatted?