0

I have a collection like: [{a: 'eXeD9', b: 399}, {a: 'eXe9', b: 35399} , xOBJs].

I am gonna search 24823293 in b field. So as I know I am have to traverse all docs, until there is a match with 24823293.

So I am confused if I create an index for b field, how it can reduces the number of docs for scanning?

Because maybe the 24823293 is not within those reduced docs.

As I am a mobile application developer, I am confused here any help.

Muhammad
  • 2,572
  • 4
  • 24
  • 46

1 Answers1

1

Because with an index the scan will be performed against the possible values of { b } (which would be stored in a time efficient data structure, like a B-tree) rather than on your whole set of documents.

Creating an index on { b } can be seen as making the value of { b } an access key to the documents themselves.

You end up with an index scan instead of a full scan, which can dramatically make the difference.

36ve
  • 513
  • 4
  • 12
  • Thank you, you mean if we dont have an index. then the scan will aplly on `a field` too ? – Muhammad Nov 08 '20 at 15:26
  • the scan would apply on the whole set of documents, with a lookup on the b field in order to verify your query predicate – 36ve Nov 08 '20 at 15:34
  • Thank you very much, if I search by `b field` will it be helpful to create index ?, because I use `$or: [{b: 'v1'}, {b: 'v2'}, {b: 'v3'}, xxx]` query and you know I have an array of objects to be compared with collection objects, so will it be still helpful to create index ? – Muhammad Nov 08 '20 at 15:38
  • absolutely. actally mongod even provides a notablescan option to make sure none of your queries makes its way to production without using an index https://docs.mongodb.com/manual/reference/parameters/#param.notablescan – 36ve Nov 09 '20 at 06:31
  • and one more question please, do we need to create index at any time (`insert, update, delete`) or just one time we create the index for a field? – Muhammad Nov 09 '20 at 08:35
  • 1
    just create the index that feats your need once, the database will use it whenever this is relevant – 36ve Nov 09 '20 at 12:44