Home > Software design >  How to search for multiple ObjectIds using MongoDB Atlas Search
How to search for multiple ObjectIds using MongoDB Atlas Search

Time:01-06

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?

CodePudding user response:

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

CodePudding user response:

One approach is to follow the $search stage with a $match stage. Then you can use the $in operator to search for multiple ObjectIds. Note that this approach has performance implications, as described here:

https://docs.atlas.mongodb.com/atlas-search/performance/#-match-aggregation-stage-usage

  •  Tags:  
  • Related