How to do exact term search using atlas search

I learned that when using atlas search with aggregation, it would require $search to be the first stage in the pipeline, thus we cannot use $match to filter the results first.

As a result, I am looking to use a way to do exact term (string) filter to help me filter the results in the $search stage.
I was looking at https://www.mongodb.com/docs/atlas/atlas-search/phrase/, but unfortunately, it is not exact filter, which may over select the results.

Question is: Is there currently a way to do exact term search within $search stage? If not, is there a plan to expand https://www.mongodb.com/docs/atlas/atlas-search/equals/ to support string as well?

Thank you!

Hi William,

Have you looked into filter option for the compound operator to see if it works for your use case?

If you’ve tested it, can you highlight the document(s) from your testing that should / shouldn’t be returned?

Regards,
Jason

Hi @Jason_Tran , thank you for your quick reply!!

My understanding with filter option is that, it would still require to pick an operator to do the actual filter work, like using equals or phrase as what I mentioned. So my question is on how to pick the right operator to help me do exact term filter.

As for the document example, consider this:

[
  {
    "fieldA": "abc",
    ...
  },
  {
    "fieldA": "abc",
    ...
  },
  {
    "fieldA": "abcde",
    ...
  },
  {
    "fieldA": "abc def",
    ...
  }
]

I would like to do exact term filter, so that when I filter by fieldA to be “abc”, it should only return the first two documents.

1 Like

Gotcha! Thanks for providing those sample documents and noting which ones you expect to be returned.

Will the keyword analyzer work for you?

Example based off your sample docs:

testdb> db.collection.find({},{_id:0})
[
  { fieldA: 'abc' },
  { fieldA: 'abc' },
  { fieldA: 'abcde' },
  { fieldA: 'abc def' }
]

Index definition for my test environment (*called "ftindex"*):

{
  "analyzer": "lucene.keyword",
  "searchAnalyzer": "lucene.keyword",
  "mappings": {
    "dynamic": true
  }
}

$search pipeline and output:

testdb> db.collection.aggregate([{$search:{index:'ftindex',phrase:{query:'abc',path:'fieldA'}}},{$project:{_id:0}}])
[ 
{ fieldA: 'abc' }, 
{ fieldA: 'abc' } 
]

You may also find the following blog post useful too regarding Exact Matches in Atlas Search.

Regards,
Jason

Yes! It works!!
Thank you @Jason_Tran

Good to learn how analyzer would help with it

1 Like

Glad to hear that helped out :slight_smile: