What is the purpose of $eq

One specific application I can see for $eq is with cases like the $not operator which requires that its value is an operator-expression.

This allows you to construct a query like:

db.zips.find({state: {$not: {$eq: 'NY'}}})

Before, the closest you could get to this semantically was:

db.zips.find({state: {$not: {$regex: /^NY$/}}})

I realize there are other ways to represent the functionality of that query, but if you need to use the $not operator there for other reasons, this would now allow it.


In filter part of an aggregation query if you need to check if some field is equal to a value you can not use assign syntax:

db.sales.aggregate([
   {
      $project: {
         items: {
            $filter: {
               input: "$items",
               as: "item",
               cond: { $eq: [ "$$item.price", 100 ] }
            }
         }
      }
   }
])

The problem was that you'd have to handle equality differently from comparison when you had some kind of query builder, so it's

{ a : { $gt : 3 } }
{ a : { $lt : 3 } }

but

{ a : 3 }

for equality, which looks completely different. The same applies for composition of $not, as JohnnyHK already pointed out. Also, comparing with $eq saves you from having to $-escape user provided strings. Therefore, people asked for alternatives that are syntactically closer and it was implemented. The Jira ticket contains a longer discussion which mentions all these points.

The clearer syntax of an $eq operator might also make sense in the aggregation framework to compare two fields, should such a feature be implemented.

Also, the feature has apparently been around since 2.5, was added to the documentation relatively late.

Tags:

Mongodb