Mongoose Population vs Indexing

32 views
Skip to first unread message

swei...@waiport.com

unread,
May 26, 2018, 9:42:19 PM5/26/18
to mongodb-user
Hey all,

Hopefully this isn't a stupid question. Not sure what would be considered best practice / preferred.

Let's say I have two collections, Users and Events, where each User can be the owner of multiple Events.

To retrieve a given users Events, is it better to:
a) Store the ID's in an Array field called 'events' on the User. When I need the Events, populate this Array
b) Create an index on the 'owner' field of the Events and perform look-ups on that key when I need a given users Events. No need to store an Array 'events' on User.

Additionally, if I wanted to take that a step further and find Events greater / less than certain dates, it seems like setting a Compound Index on owner/date is the way to go. Thanks!

--Sam

Andrew Nessin

unread,
May 28, 2018, 12:51:52 AM5/28/18
to mongodb-user
The answer to your first part of the question (whether to store array of event ids in owner collection, or store the owner id in the events collection) is a modelling question that has awesome explanation in this blog post

In brief, in depends on the number of events a user will be associated with at a given time. If it is a near constant and less than, say, a 1000, then the first approach of storing the event ids in an array in owners collections is a good idea. If the number of events for a user grows indefinitely, then storing the owner id in the events collection is the good idea. Please check out the blog post for in depth reasoning for this and other factors that you have to consider before deciding on the final approach.

After you decide on the linking strategy, then you can think about the compound index that maybe needed. The index you have mentioned would work fine if you decide to embed the owner ids in every event documents.

Best Regards,
Andrew

swei...@waiport.com

unread,
May 30, 2018, 7:29:53 AM5/30/18
to mongodb-user
Thanks for your response, Andrew!

Appreciate your help and the blog post.

Reply all
Reply to author
Forward
0 new messages