Om Solari
Om Solari

Reputation: 217

MongoDB query by foreign key

I have two collections:

USERS:

REVIEWS:

I would like to findAll REVIEWS Where sex=f and age>18

( I dont want to nest because the reviews collection will be huge )

Upvotes: 3

Views: 2305

Answers (2)

hhh
hhh

Reputation: 2769

You should include user's data into each review (a.k.a. as denormalizing):

{ id:777777 , user: { id:"aaaaaa", age:19 , sex:"f" } , text:"some review data" }
{ id:888888 , user: { id:"aaaaaa", age:19 , sex:"f" } , text:"some other review data" }
{ id:999999 , user: { id:"bbbbbb", age:20 , sex:"m" } , text:"mome review data" }

Here, read this link on MongoDB Data Modeling:

A Note on Denormalization

Relational purists may be feeling uneasy already, as if we were violating some universal law. But let's bear in mind that MongoDB collections are not equivalent to relational tables; each serves a unique design objective. A normalized table provides an atomic, isolated chunk of data. A document, however, more closely represents an object as a whole. In the case of a social news site, it can be argued that a username is intrinsic to the story being posted.

What about updates to the username? It's true that such updates will be expensive; happily, in this case, they'll be rare. The read savings achieved in denormalizing will surely outweigh the costs of the occasional update. Alas, this is not hard and fast rule: ultimately, developers must evaluate their applications for the appropriate level of normalization.

Upvotes: 2

user1480400
user1480400

Reputation:

Unless you de-normalize REVIEWS collection with your search attributes, MongoDB does not support querying another collection in a single query. See this post.

Upvotes: 1

Related Questions