4

I'm pretty new with Mongodb, I want to manage one-to-one, one-to-many and many-to many relation among 2 or multiple collections but not documents. How to deal with it by Java code? I don't have example at this moment, just want to get some general informations. thx!!

1
  • There's no formal link between collections or documents in MongoDB (as it's schema-less). You'll need to explain what you're looking for and provide an example. Commented Aug 13, 2013 at 16:06

2 Answers 2

3

MongoDB is schemaless, so no schema and no relations between documents on collection level.

But, you can link some (or all in your case) documents from one collections to documents in another colletion with DBRefs:

> db.users.insert({_id : a, name : "Drake", age : 15})
> db.pets.insert({name : "Booch", userId : {"$ref" : "users", "$id" : a}})
> db.users.find()
{ "_id" : ObjectId("520aaf5cfbb9bb87c072aa43"), "name" : "Drake", "age" : 15 }
> db.pets.find()
{ "_id" : ObjectId("520aafecfbb9bb87c072aa44"), "name" : "Booch", "userId" : DBRef("users", ObjectId("520aaf5cfbb9bb87c072aa43")) }

Here, userId field in pets becomes a DBRef after insert.

It is not like foreign keys in RDBMS, but more like a metadata, that helps application to link entities. And it is your job as a developer, to link them programmatically, but not with a DB query.

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

Comments

0

The primary decision here is whether to embed or to use references.

I would suggest Embedding to de-normalize data, store two related pieces of data in a single document. This way operations within a document are less expensive for the server than operations that involve multiple documents.

Check out this and this link.

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.