1

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?

3
  • In MongoDB collections cannot be joined. What functionality are you trying to provide? Commented Aug 30, 2012 at 12:57
  • May I know whats the purpose of linking(dbref) in mongodb? is it not for ensuring primary and foreign key relationship? my functionality is to query the fields by joining these two collections? Commented Aug 30, 2012 at 12:59
  • It does not ensure anything. DBRef does exactly what the names implies. It provides a cross-database, cross-collection reference to a document. It is merely a storage convention and is not backed by any sort of server functionality. Commented Aug 30, 2012 at 13:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.