Reputation: 2148
Hi i´m completely newbie with mongodb, i come from SQL Server, i have the following doubt If a have the structure bellow:
Collection: tv
"_id": ObjectId("123456abc"),
"brand": "Sony",
"model": "Bravia",
"price": 1000
Collection: tvcomments
"_id": "_id": ObjectId("456789def"),
"tv": ObjectId("123456abc"),
"comments": [
{
"user": ObjectId("413212eop"),
"text": "Very nice TV"
}
]
I´d like to get tv with their comments, but i don´t find a example to do this, maybe is not possible?
Upvotes: 1
Views: 122
Reputation: 8846
One difference between MongoDB and SQL is that there are no JOIN
s in MongoDB. The preferred way to model data in MongoDB is to embed documents inside each other instead of separating them out and referencing them by ObjectId.
Your current way of doing things will require two trips to the database, one to get the TV and one to get the comments. Unless you're planning to reference the comments in a place where you wouldn't be referencing the TV (unlikely) then you can just put the comments in the TV document directly. Now you get the comments "for free" when you pull the TV documents.
{
"_id": ObjectId("123456abc"),
"brand": "Sony",
"model": "Bravia",
"price": 1000,
"comments": [
{
"user": ObjectId("413212eop"),
"text": "Very nice TV"
}
]
}
Notice that I left the reference to the user instead of embedding that in the TV document. There are cases where you'll need to just perform multiple queries to get your data because embedding is not the proper relationship.
See here for more info: http://docs.mongodb.org/manual/core/data-modeling/
Upvotes: 3