Atlas Search Autocomplete on an array of object

Hi Jason, thanks for your response. Since I had a hard time making it, here is an implementation of this use case that works for me (it might help others):

The search index JSON on mongo Atlas

{
  "mappings": {
    "dynamic": false,
    "fields": {
      "name": {
        "type": "autocomplete"
      },
      "roles": {
        "dynamic": true,
        "type": "embeddedDocuments",
        "fields": {
          "externalId": {
            "type": "autocomplete"
          },
          "phone": {
            "type": "autocomplete"
          }
        }
      }
    }
  }
}

The query

db.entities.aggregate([
  {
    "$search": {
      "compound": {
        "should": [
          {
            "autocomplete": {
              "query": "search query input",
              "path": "name"
            }
          },
          {
            "embeddedDocument": {
              "path": "roles",
              "operator": {
                "compound": {
                  "should": [
                    {
                      "autocomplete": {
                        "path": "roles.externalId",
                        "query": "search query input"
                      }
                    },
                    {
                      "autocomplete": {
                        "path": "roles.phone",
                        "query": "search query input"
                      }
                    }
                  ]
                }
              }
            }
          }
        ]
      }
    }
  },
  {
    $addFields: {
      "score": { $meta: "searchScore" }
    }
  }])

3 Likes