Search index filtering

Hello,

You can use a compound query using a combination of “filter” and “must” to obtain the functionality of $match, this is explained in detail here.

I did this example below with two records having same description and different companyId.

Atlas atlas-whhaeg-shard-0 [primary] test> db.companies.find()
[
  {
    _id: ObjectId("63593dc870ca422a31030ded"),
    companyId: '456-678',
    description: 'this is a description'
  },
  {
    _id: ObjectId("635945a370ca422a31030dee"),
    companyId: '45232-678676',
    description: 'this is a description'
  }
]

Using the below $search specifying the “must” clause to match companyId with “456-678” and having a filter on description with part of the description, in this case the word “this”.

Atlas atlas-whhaeg-shard-0 [primary] test> db.companies.aggregate([
...   {
...     "$search": {
...     index: 'companyId',
...       "compound": {
...         "filter": [{
...           "text": {
...             "query": ["this"],
...             "path": "description"
...           }
...         }],
...         "must": [{
...           "text": {
...             "query": "456-678",
...             "path": "companyId"
...           }
...         }]
...       }
...     }
...   }
... ])
[
  {
    _id: ObjectId("63593dc870ca422a31030ded"),
    companyId: '456-678',
    description: 'this is a description'
  }
]

As you can see the “must” clause forced the search to return only documents that matched the specified companyId.

There are various other examples you can try using options of the “compound” section of $search in the documentation link below:

I hope you find this helpful.

Regards,
Elshafey

1 Like