Reputation: 463
I have collection called company with
{
_id: ObjectId("1111"),
name: 'ABc COrp',
address: {
Street: '124 Main Street'
city: 'San Diego'
state: 'California'
zip: "92115"
}
vendor: [{
vendor_id: ObjectId("1234")
}, {
vendor_id: ObjectId("4567"
}]
}
}
// vendor collection
{
_id: ObjectId("1234"),
name: 'foodCA company',
company: [company_id: ObjectId('11111')]
}
Now i have types of vendor like food, office supplies,etc for a company. Vendor and company has many-many relationship.
Can i use dbref (http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef) for many-many when I am already using embedded document structure)
Thank you! I am a newbie to mongoDB. I apologize for my ignorance.
Upvotes: 0
Views: 595
Reputation: 222999
Based on official documentation are two options:
dbRef
Keep in mind that:
To resolve DBRefs, your application must perform additional queries to return the referenced documents. Many drivers have helper methods that form the query for the DBRef automatically. The drivers 1 do not automatically resolve DBRefs into documents.
Because of these some people (1, 2, 3 and I by myself do not see a point of using them). Also dbRef allows you to reference not only another collection, but also another database. (I have never found it useful, but it does not means that other have not).
Manual referencing:
I prefer this method because it is super simple and easy to read. You have companies and vendors, so
{
companyID : 1,
vendors: [1, 3, 19]
}
Note that there is no reason of putting each vendor as an object as you have done. Have small amount of different vendors, than you can do: { companyID : 1, vendors_food: [1, 3], vendors_drinks: [17] }
Many vendors with different types, than you can do what you have done:
{
companyID : 1,
vendors: [{
'type' : 'drink',
'id' : 18
},{
'type' : 'food',
'id' : 3
}],
}
And after you found vendors for your company [1, 6, 29]
, you can combine them and do only one db request to find info about all of them with $in:
db.vendors.find({
'_id': {
$in: [1, 6, 29]
}
});
Note, that this is only my preference of working with mongo.
Upvotes: 1