Using operators like $eq within aggregator pipelines

I am not clear on the syntax of operators like $eq when used within the aggregator pipeline
In case of use in pipeline, the syntax takes this form:
{$match: {$and: [ {“languages”: {$eq: “French”}}, {“languages”: {$eq: “Marathi”}} ] }}

But in case of find command it takes this form

db.inventory.find( { qty: { $eq: 20 } } )

I am unable to form a clear understanding of why the same operator (at least written the same way) has different syntax and why. Can someone point me to good explanation that can help me clarify this?

Thank you

Pipeline: {$match: {$and: [ {“languages”: {$eq: “French”}}, {“languages”: {$eq: “Marathi”}} ] }}

Find: db.inventory.find( { qty: { $eq: 20 } } )

In both cases the syntax is same: {“fieldname”: {$eq: “value”}}. I do not understand why you think it is different in these two cases.

There is a better alternative to $eq. Instead of using { qty: { $eq: 20 } }, use { qty: 20 }

Hey @MANAV_PUROHIT_36789 & @Mahesh_56388

So there deffinately is a difference. See the below

Query Operator $eq

{ <field>: { $eq: <value> } }

Aggregation Expression

{ $eq: [ <expression1>, <expression2> ] }

And yes indeed there are numerous Query operator that look like and function similar to the Aggregation Expression Operator

With the second only being able to

These expression operators are available to construct expressions for use in the aggregation pipeline stages.

$match has this to say

$match takes a document that specifies the query conditions. The query syntax is identical to the read operation query syntax; i.e. $match does not accept raw aggregation expressions. Instead, use a $expr query expression to include aggregation expression in $match .

Hope that clears it up. I know it can be a bit confusing.

1 Like