ERROR: Following filter query in find method works but gives error while using aggregation operator $match. Why?

STATEMENT 1. db.collection.aggregate( [ { $match: { “field1”:“value1”, $or: [ {“field2”: “value2”}, {“field3”:“value3”} ] } } ] );
STATEMENT 2. db.collection.find( { “field1”:“value1”, $or: [ {“field2”: “value2”}, {“field3”:“value3”} ] } );

Question #1. 1st statement would give an error whereas the 2nd will run.
Why can’t we use a field1 and or condition together in the 1st statement?

Question#2.
If I remove field1 from 1st statement, then aggregation pipeline won’t throw any error.
Meaning that db.collection.aggregate( [ { $match: { $or: [ {“field2”: “value2”}, {“field3”:“value3”} ] } } ] ); would work. Why?

Hello @Ashwin_Mahajan, welcome to the MongoDB Community forum!

Question #1. 1st statement would give an error whereas the 2nd will run.

What is the error you are getting?

Try using this filter and see if you still have the error:

{ field1: "value1", $or: [ { field2: "value2" }, { field3: "value3" } ] }

The quotes “” you had used might have caused the error. Use the quotes (double or single) which are straight: "", or ''. Note the difference:

“” ""

Hi @Prasad_Saya,

It’s working fine for me now. I made a typo in the query. Thanks for the help though. Appreciate it!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.