Cant do sort after $search MustNot compound

Hi,

I got problem with sort and MustNot in $search compound

[
    {
        '$search': {
            'compound': {
                'must': [], 
                'mustNot': [
                    {
                        'phrase': {
                            'query': 'bar', 
                            'path': [
                                'title', 'description'
                            ]
                        }
                    }
                ], 
                'should': [], 
                'filter': []
            }
        }
    }, {
        '$sort': {
            'ratemin': 1
        }
    }
]

I got this every time :

{"errorCode":"OPERATION_ERROR","message":"Reason: [23:47:46.227] Error running aggregation for '****.testlots' on process '****-cluster-shard-00-01-****.mongodb.net:27017' : [23:47:46.227] Error calling aggregation in coll (*****.testlots) for connParams=*****-cluster-shard-00-01-****.mongodb.net:27017 (local=false) partialRes:[[]] : [23:47:46.227] Error executing WithClientFor() for cp=****-cluster-shard-00-01-****.mongodb.net:27017 (local=false) connectMode=SingleConnect identityUsed=mms-automation@admin[[MONGODB-CR/SCRAM-SHA-1]][24] : (MaxTimeMSExpired) Remote error from mongot :: caused by :: operation exceeded time limit","version":"1","status":"ERROR"}

But if i do same pipeline by changing mustNot by must it’s working.

( 500k documents in collection ) ( M40 )
Any idea ?

Thanks.

@Jonathan_Gautier one way to accomplish the sort would be to use the near operator. It will only work for numeric, date, or geo data types. Try it out and let me know if that helps.

For the query you provided, it might look something like this:

[
  {
      '$search': {
          'compound': {
              'must': [
                {
                  'near': {
                    'path': 'some _numeric_field',
                    'origin': 0, //0 for ascending ||  an integer larger than total results for descending
                    'pivot': 1
                  }
                }
              ], 
              'mustNot': [
                  {
                      'phrase': {
                          'query': 'bar', 
                          'path': [
                              'title', 'description'
                          ]
                      }
                  }
              ], 
              'should': [], 
              'filter': []
          }
      }
  }
]

XD @Marcus

Little tricky but i will try !

I hope we can make simple sort and count directly in $search in future :wink:

1 Like