Chapter-4 Lab 2: Array Operators

Using the sample_airbnb.listingsAndReviews collection find out how many documents have the “property_type” “House”, and include “Changing table” as one of the “amenities”?

For the above question, the query I came up with is: db.listingsAndReviews.find({"$expr":{"$and":[{"$eq":["$property_type","House"]},{"amenities":{"$all":["Changing table"]}}]}}).count()
which gave me an error:
uncaught exception: Error: count failed: {
“operationTime” : Timestamp(1606200951, 2),
“ok” : 0,
"errmsg" : “Unrecognized expression ‘$all’”,
“code” : 168,
“codeName” : “InvalidPipelineOperator”,
“$clusterTime” : {
“clusterTime” : Timestamp(1606200951, 2),
“signature” : {
“hash” : BinData(0,“1F1bL+fwCsA/7IUfqtLvovuQbq0=”),
“keyId” : NumberLong(“6890856103911882754”)

Thus I modified my query to:
db.listingsAndReviews.find({"$expr":{"$and":[{"$eq":["$property_type","House"]},{"amenities":"Changing table"}]}}).count()
This gave me a count of ‘606’, but the grader says it’s wrong answer. Please help me find out my mistake.

Thanks & Regards,

  • Riz M

Hi @Riyaz_Ali,

I can’t say if this will yield the right result, but still some ideas:

$expr takes an expression as its input. The first slice is fine, but $all is not a valid expression operator.

We could re-write the query as:

"amenities":{"$in":["Changing table"]} 

// or

"amenities": "Changing table" 

Again, for the second block of code, a plain object isn’t a valid expression.


Thank you for your response Santiago!

1 Like

This was the query that I used :
db.listingsAndReviews.find({“property_type”:“House”, “amenities” : {"$all" : [“Changing table”]}}).count()

And this gave me correct answer

Hi @Mitchell_Anthony , I wrote almost the same as you did but with a little difference that is enough to not get a result:

db.listingsAndReviews.find({"$and":[{"property_type":"House"},{"amenities":{"$all":"Changing table"}}]})

The only difference I can find is the square brackets in Changing table . But I’am wondering why would that make any difference…

But like I wrote you in another thread, the $and is redundant because there is an implicit AND already between property_type and amenities clauses. So @Mitchell_Anthony’s version is simpler and less error prone as the number of braces and brackets is smaller.

Hi @steevej, yes , you are right about the $and operator , that is just a bad habit I need to forget.

I was mentioning the square brackets difference though on the word “Changing tables” !

Hi @Simao_Bonvalot , I saw your query but it is not going to work as we are using array operator i.e “$all”.
Basic syntax of using this operator is -
{ <field>: { $all: [ <value1> , <value2> ... ] } }
As it is an array operator so we have to provide the value inside square brackets. This is what I think, and I know till now . For more details you can refer this document -

1 Like