Search code examples
mongodbpymongomongodb-querymongodb-indexes

Index for query with "field": {$not: {$elemmatch: {...}}?


Why is this query not using this index when searching documents like these?

My Query:

{ 
  "unique_contact_method.enrichments": {
    "$not": {
      "$elemMatch": {
        "created_by.name":enrichment_name
}}}}

My Index:

{ key: { "unique_contact_method.enrichments.created_by.name": 1 }, ... }

My Documents:

{
    "created_at": "...",
    "unique_contact_method": {
        "type"  : "...",
        "handle": "...",
        "enrichments":  [{
            "created_at"    : "...",
            "created_by"    : {
                "name"      : "...",
                "version"   : "..."
            },
            "attrs" : { /* ... */ }
            }, /* ... */
        ],
        "master_id_doc_id": "..."
    }
}

Solution

  • $not can be fussy with indexes. Rewrite the query as:

    {'unique_contact_method.enrichments.created_by.name': {$ne: enrichment_name}}
    

    That should definitely use the index.