2

If I setup a Model with a discriminator key mongoose automatically prefixes all queries with the discriminator key.

But if I define some keys as index: true the indexes that are created are not prefixed by the discriminator key. Instead they are simple indexes with a single key.

Isn't this suboptimal? Shouldn't all indexes be compound indexes of the discriminatorKey (e.G. __t) and the key I want to index?

And if yes should I instead of defining indexes at the path level (via index: true) prefer to set them like this:

Event.index({ __t: 1, type: 1 });
Snowball
  • 1,402
  • 2
  • 17
  • 31
  • Not necessarily. `QueryPlanner` analyze your query to check what index combination fits better to execute your query (check yourself: `db.event.find({__t:"foo", type:"bar"}).explain()`). So adding `__t` won't change your query performance. – Valijon Feb 21 '20 at 17:40

1 Answers1

1

no its not suboptimal. The discriminator key makes mongoose understand which schema/model you are using and creates an instance of one for you automatically when eg. a query comes back. Mongoose doesn't know how you will be using that additional key (maybe you want to query all of your types for a specific value? or you want to make a unique index on a name over all your types?), so creating 'basic' indexes via the path value just does what you describe, it just makes an index.

if you have the usecase that these are strongly linked, you can create compound index or sparse indexes.

japrescott
  • 4,736
  • 3
  • 25
  • 37
  • thanks for your answer. So you can confirm that for performance reasons if I do have a usecase where they are strongly linked (like always only quering over a single discriminator type, not on all types) it would make sense to manually create compound indexes instead? – Snowball Feb 21 '20 at 17:20
  • yes! But its always better safe [to see what mongodb is doing under the hood with your index](https://docs.mongodb.com/manual/reference/explain-results/) and see if your indexes are correct – japrescott Feb 26 '20 at 12:53