rajan sthapit
rajan sthapit

Reputation: 4364

Relational querying in mongo

I have the following models in my app and I am using mongoid

User, Account, Office and Leads A user has many accounts and an account belongs to a user An account has many offices and an office belongs to an account An office has many leads and a lead belongs to an office

Now I want to query such that I want to get the leads belonging to the offices of accounts of a user, like `

@accounts = Account.where(:user => user)

Now I want to get the leads of the offices belonging to @accounts. Is there a decent way to accomplish it? or I have to iterate over each account and get the offices belonging to that account and then ultimately find the leads.

I could persist the account information in the leads itself so that they contain both the account and office information so that I can query in one shot. But is that the right way?

Suggestions?

Upvotes: 0

Views: 178

Answers (1)

dm.
dm.

Reputation: 2002

If these are "contains" relationships consider embedding rather than linking. For example if all leads belong to one office you could embed them therein:

{ office:"...", leads : [ { ... }, { ... } ] }

Likewise the offices could be embedded in an account document. And so forth.

However whether the above makes sense depends on the operations you plan to do (if fully embedded a query such as "give me all leads" if more work). Also there is a maximum document size of 16MB.

Likely some combination of embedding and linking is appropriate. When linking you have to do it client side as you mentioned. See the schema design and "reaching into objects" pages on mongodb.org.

Upvotes: 1

Related Questions