Use $search instead of $match when using $in conditions in MongoDB Atlas Search

296 Views Asked by At

During a recent training, I learned about the benefits of using the $searchoperator. I would like to modify my $match query to use $search instead. However, I couldn't find an equivalent for the $in operator.

When the fields need to match a single ObjectId, there is no problem, I can use the compound operator with must + equals and it works.

The problem arises when I have multiple ObjectId values. Again, if it's only for one field, I could use should + equals while specifying minimumShouldMatch: 1.

But I'm not sure how to handle it if I have multiple fields with multiple ObjectId values... How should I approach transforming a query like this using the $search operator?

 { '$match':
     { '$and':
        [ { customer:
             { '$in': [ 5f3d6c51f5b2ed74fe93dd60, 5c221b4e4d17f1734806b4a5 ] } },
          { carrier: { '$in': [ 'carrier1', 'carrier2', 'carrier3' ] } },
          { status: { '$in': [ 'late', 'idle', 'delivered-late' ] } },
          { createDate: { '$gte': 2023-06-01T04:00:00.000Z } },
          { createDate: { '$lte': 2023-07-01T03:59:59.999Z } } ] } 
}
1

There are 1 best solutions below

0
Rudr Thakur On

You can either use the filter option in the $search query

   $search: {
      "compound": {
        "filter": [{
          "queryString": {
            "defaultPath": "role",
            "query": "CLIENT OR PROFESSIONAL"
          }
        }]
      }
    }

Or you can use the $in operator like mentioned here in the docs but it only allows certain data types

https://www.mongodb.com/docs/upcoming/reference/operator/query/in/#mongodb-query-op.-in