1

I have an array in documents, but different queries use it in different way. It could be an $exists query or search by nested array's item fields. Which indexes should i make in these cases?

Also, i use MongoDb v. 3.0.2 & Official c# driver v. 2.0

Vladyslav Furdak
  • 1,765
  • 2
  • 22
  • 46
  • Indexing arrays - MongoDB indexes each value of the array so you can query for individual items – gpullen Sep 15 '15 at 15:00
  • 1
    Not enough info here but I am guessing you want to make an index on the array parts i.e. `{'s.c':1,'s.b':1}` rather than on the entire array – Sammaye Sep 15 '15 at 15:10
  • I need a separate index for $exists query and for query for nested field in array's objects – Vladyslav Furdak Sep 15 '15 at 15:19

1 Answers1

3

When you want to search by nested array's item fields, then you will need separate indexes for different fields or field-combinations you query by. Which individual or compound indexes make sense here depends on what queries exactly you perform.

MongoDB has no "wild-card indexes" which index all fields of a given sub-document. However, you can sometimes emulate that behavior by replacing a sub-document with an array of { key:"key", value:"value" } objects.

Philipp
  • 67,764
  • 9
  • 118
  • 153
  • What about indexing for only `$exists` query ? – Vladyslav Furdak Sep 16 '15 at 11:02
  • @MongoUser101 do you want to know if the array as a whole exists or if a specific array entry exists? – Philipp Sep 16 '15 at 11:03
  • i want to know if the array as a whole exists – Vladyslav Furdak Sep 16 '15 at 11:05
  • @MongoUser101 In that case a [sparse](http://docs.mongodb.org/master/tutorial/create-a-sparse-index/) ascending (`field:1`) or descending (`field:-1`) index on the array should work. I am not sure if a [hashed index](http://docs.mongodb.org/master/tutorial/create-a-hashed-index/) would work. The documentation says that hashed indexes collapse subdocuments into one value and that it does not work on array entries, but it is unclear about if it treats arrays as one value or skips them altogether. – Philipp Sep 16 '15 at 11:32