Ch4 lab $expr question to query

I tried the $expr lab first with the following query
db.companies.find({"$expr":["$permalink", “$twitter_username”]}).count()

then I got 1599 which is the total number of documents in the collection.

I know that the correct answer is the following, but I wonder why the above did not work. I understood that $eq is implicitly active.
db.companies.find({"$expr":{"$eq": ["$permalink", “$twitter_username”]}}).count()


Hi @Rasha_Elsayed

Welcome to the MongoDB community forums! :four_leaf_clover:

I understood that $eq is implicitly active.

This assumption is not correct. $expr requires an operator to be explicitly declared in it be it $eq or any other comparison operators and this is why your second query worked.

Now for your first query, $expr without any operators in the expression evaluates to a constant value which would be equivalent to doing:


which is why the query just returned all the documents in that collection to you, hence it is important to mention the operators. For more information and examples, check out the $expr operator documentation.

Let me know if you have any further doubts.



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