How would you optimize this query?

{
          "accountId": "...",
           "buildingId": {
            "$in": [
              "...",
              // 50 more
            ]
          },
          "created": { "$gte": ISODate(...), $lt: ISODate(...) },
        }

I have an index for:
{ accoundId: 1, buildingId: 1, created: 1}
and for:
{ accoundId: 1, created: 1}

I noticed when I get too many $in elements, it will switch from the more specific index, to the more generic one. The explain:

"planSummary": "IXSCAN { accountId: 1, created: -1 }",
  "keysExamined": 34810,
  "docsExamined": 34810,
  "cursorExhausted": true,
  "numYields": 43,
  "nreturned": 29,
  "queryHash": "E8C5EB6E",
  "planCacheKey": "6E1958CA",
  "reslen": 11692,
  "locks": {
    "ReplicationStateTransition": {
      "acquireCount": {
        "w": 51
      }
    },
    "Global": {
      "acquireCount": {
        "r": 51
      }
    },
    "Database": {
      "acquireCount": {
        "r": 51
      }
    },
    "Collection": {
      "acquireCount": {
        "r": 51
      }
    },
    "Mutex": {
      "acquireCount": {
        "r": 8
      }
    }
  },
  "storage": {
    "data": {
      "bytesRead": 28065577,
      "timeReadingMicros": 23823
    }
  },
  "protocol": "op_msg",
  "durationMillis": 1835,
  "v": "4.4.10"

Hi @Ryan_Nichols ,

Please note that, when there are more than 200 $in elements used query planner no more consider them as a quality search but consider it as a range. The query planner evaluates the plan generated from multiple execution stats and selects the one which is best. you can see all the execution stats using allPlansExecution.

This may be the reason for your query to choose the second index over first. You might be aware that we have $hint option to force the query planner to choose the index, but it is not a recommeneded as query planner will choose the better one always.

I hope my answer clears your doubt.
Thanks,
Darshan