4

I have the following schema:

{
   name: String,
   phones: [
        {
            number: String,
            type: String
        }
   ]
}

How do I index phones.number so that I can write something like:

collection.aggregate([{
       "$search":{ 
            "compound":{
                  "should":[
                      {"autocomplete":{"query":"012345","path":"name"}},
                      {"autocomplete":{"query":"012345","path":"phones.number"}}
                  ]
             }
         }
}])

The docs here give an example for an array of strings but not an array of objects.

Mika
  • 5,807
  • 6
  • 38
  • 83

1 Answers1

5

As per this answer, indexing by a property of a subdocument in an array is supported. Just create an index by phones.number.

See the documentation for more information.


EDIT

I was confusing standard indexing with indexing for Atlas Search. From the documentation, you should be able to index an array of documents this way:


{
  "analyzer":"lucene.standard",
  "searchAnalyzer":"lucene.standard",
  "mappings":{
    "dynamic":false,
    "fields":{
      "name":{
        "type":"string",
        "analyzer":"lucene.standard"
      },
      "phones":{
        "type":"document",
        "fields":{
          "number":{
            "type":"string",
            "analyzer":"lucene.standard"
          },
          "type":{
            "type":"string",
            "analyzer":"lucene.standard"
          }
        }
      }
    }
  }
}

Chris
  • 4,009
  • 3
  • 21
  • 52
  • 2
    Dot notation is actually not supported in the way you are thinking. Users need to specify the phones field as a type `document` and its object members accordingly. See the documentation here on index definitions: https://docs.atlas.mongodb.com/reference/atlas-search/index-definitions#document – Nice-Guy Jan 04 '21 at 16:09
  • @Nice-Guy Does the example on this link not apply for a multi key index in this context? https://docs.mongodb.com/manual/core/index-multikey/ – Chris Jan 04 '21 at 20:26
  • @Nice-Guy Sorry, I see I have confused starboard indexing with indexing for Atlas Search. – Chris Jan 04 '21 at 20:39
  • Thanks it helped. @Chris, does the order of the indexed fields of atlas search matters for our query(highly selective / least selective ) to perfom well ? – Firoj Siddiki Aug 23 '21 at 11:29
  • I’m not sure how much the order matters. Sorry. Glad the answer helped! – Chris Aug 24 '21 at 19:17
  • 1
    yayyyÿÿyyyyyyyy – nrmad Nov 02 '21 at 17:22
  • 2
    @FirojSiddiki might be little late but no the order of fields in index mapping doesn't matter in mongodb atlas indexes. – Pawan Saxena Jun 14 '22 at 17:34