Search code examples
mongodbmongodb-atlasmongodb-atlas-search

How to search for multiple ObjectIds using MongoDB Atlas Search


I have documents in a MongoDB collection that reference ObjectIds in a different collection. For example, my Orders collection has documents with a CustomerId.

Using MongoDB Atlas search, I've defined an index that allows me to search the CustomerId field with this syntax:

{
  "index": "Orders",
  "equals": {
    "path": "CustomerId"
    "value": new ObjectId("5m5....")
  }
}

(The above snippet is from the $search stage of my aggregation pipeline.)

But now I need to perform an OR search using multiple customer Ids. Unfortunately, I can't just specify an array of ObjectIds when using the equals operator. https://docs.atlas.mongodb.com/atlas-search/equals/

What are my options for searching a MongoDB Atlas Search index with multiple ObjectIds?


Solution

  • You can use a compound query with a should clause and minimumShouldMatch set to 1 - https://docs.atlas.mongodb.com/atlas-search/compound/.