Search code examples
mongodbdatabase-performanceprojectionquery-performance

MongoDB Projection Performance - or just many small documents?


I'm building a collection for User Settings / Preferences and other user related stuff.

At the moment a document look like this:

{
  "_id": "USER_ID",
  "setting1": { "foo": "bar" },
  "setting2": true,
  "setting3": "this might be a huuuuge email template",
  ...
}

And I query stuff by the user's id and then I use a projection to get the settings I need, i.e.:

find( {"_id":"USER_ID"} , {"setting2":1, "setting3":1} )

What if such a document will grow to 5 MB and has 500 keys? Will this still perform well?

Or should I use a document per USER_ID-SettingsKey-Tuple? (With index on user and key) i.e.:

{
  "_id":ObjectId("..."),
  "user": "USER_ID",
  "key": "setting1",
  "value": { "foo": "bar" }
}
{
  "_id":ObjectId("..."),
  "user": "USER_ID",
  "key": "setting2",
  "value": true
}
...

And then query with find({user:"USER_ID", key:{$in:[setting1, setting2]}})

What will perform better for many (and huge) settings per user?


Solution

  • Nesting is better. fewer documents = higher performance. For the best performance, I'd break your settings into 22 categories with 22 keys in each, that way accessing one property would take a maximum of 22+22=44 steps instead of 500. Of course, only break them into sensible groups, if at all.

    insert stupid quote about premature optimization here