Quizz - Array question

My question is related to the Quizz in the course:

db.listingsAndReviews.find( { “amenities”: “Free parking on premises”, “amenities”: “Wifi”, “amenities”: “Air conditioning”, “bedrooms”: { “$gte”: 2 } } ).pretty()

This is incorrect .

This query will return all documents that contain at least one of each of those elements. This means that some of these documents won’t match the question prompt and contain only one or two of the required elements.

I don’t understand this answer, I thought that when we don’t put an operator, then the default operator is implicit AND, while the answer implies that the OR operator will be used in this case, could you please explain in more details?

Thank you

Hi! Good question,

Not sure about this particular exercise, but for the and vs or question, something like this could be run:

 db.random.insert({"amenities":["a","b","c"]})
 db.random.find({amenities:"a", amenities:"d"})

If this were “or” the there should be a match, but instead there is none.

db.random.find({amenities:"a", amenities:"b"}) matches as expected.


As for the exercise itself, someone else may give you feedback :slight_smile:

A query is a JSON document.

A JSON document cannot have 2 fields with the same key.

So

is wrong as amenities appears 3 three times.

The fact that

returns 0 document is not related to the fact that there is an implicit AND. It is because, the query is equivalent to {amenities:“d”}. The 2nd amenities override the first one. Try the following in the shell:

query = {amenities:"a", amenities:"d"}

Also try

db.random.find({amenities:"d", amenities:"a"})

@steevej-1495 That’s unexpected for me, but yet quite interesting. I imagined there would be like a loop through the key values.

Thanks

Hi @Amine_BOUFATAH,

Thanks for surfacing this. We will update the 'detailed explanation` for this option to make it more clear.

~ Shubham

Thank you all for the explanations and for your help :slight_smile:

I tried something to further confirm that

db.random.find({amenities:1, amenities:2})

is equivalent to

db.random.find({amenities:2})

and it works. Try running

db.random.find({amenities:1, amenities:2}).explain().queryPlanner

The interesting part is the field parsedQuery.

1 Like

Just realized {a:"a", a:"b"} wouldn’t make logical sense to mean “and”. By reading the queryPlanner for something else.

But you can combine like this: {a:{$exists:true, $ne:null}} afaik. (the other way, is parsed as a:"a", a:"b"). Same thing using a:{$eq:"a", $eq:"b"} (parsed a:"b"). Which seems right now…