Anita
Anita

Reputation: 61

MongoDB, how to make a link between collections with JAVA code

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!!

Upvotes: 4

Views: 2273

Answers (2)

shantanusinghal
shantanusinghal

Reputation: 724

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.

Upvotes: 0

madhead
madhead

Reputation: 33451

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.

Upvotes: 3

Related Questions