{
field_1: {
A: true,
B: true
}
}
Instead of creating indexes on field_1.A
and field_1.B
, what happens if I create an index on just field_1?
db.coll.createIndex( { field_1: 1} )
CodePudding user response:
The purpose of indexes is to improve query performance. So while we can make statements like "the index will have objects for its key values" and "write throughput will be marginally impacted", I don't think we can make any helpful statements about how query performance will change without information about the queries you will be running.
Here are two general things that may be helpful though:
- You probably want to define the index on the nested fields that are being queried.
- The
explain
output should quickly give you a sense for if an index is being used for a query or not.
Assuming that you execute a query such as { 'field_1.A': 123 }
, the index on { field_1: 1 }
will not be used. You can determine that via the presence of the COLLSCAN
in the explain
output (playground demonstration here). By contrast, the index on { "field_1.A": 1 }
is used just fine for the query. This is determined by the presence of the IXSCAN
stage in the explain
output (playground demonstration here).
Broadly, it is uncommon to query on objects as opposed to individual field values. When doing so, the entire structure (and ordering) of the object matters. If you did happen to be querying on the full object then the accompanying index would be appropriate and used (playground demonstration here).