Reputation: 1105
I am newbie to mongodb. I need to link two collections something like in relationaldb one using primary key and foreign key concept.
I know mongodb doesnot support joins.
comments
{ uid:12345, pid:444, comment="blah" }
{ uid:12345, pid:888, comment="asdf" }
{ uid:99999, pid:444, comment="qwer" }
users
{ uid:12345, name:"john" }
{ uid:99999, name:"mia" }
in comments collections, uid --> primary key, in users, uid--> foreign key.
how to address this relationship in mongodb while inserting the collections in it? how to reference it?
could you send me the mongodb command for it?
Upvotes: 1
Views: 1715
Reputation: 69773
A common novice error when using MongoDB is to treat it as if it were a relational database.
You usually don't need your own IDs in MongoDB, because every document automatically has the _id field (which is a GUID).
To reference another entity in MongoDB, you can use a DBRef object. So every comment document should have a field "author" which is a DBRef to a document in the users collection. Alternatively, you can just use the GUID of the object you want to reference as value for "author".
See http://docs.mongodb.org/manual/applications/database-references/ for details.
About putting the document and the documents it references together: you have to do that on the application level when loading the document. The DBRef class in the MongoDB Java driver has the fetch() method which automatically fetches the document it references. This makes this quite trivial to implement.
Upvotes: 1