Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo $and selector

How does mongo $and selector work? I have trouble getting correct results back.

Let's say I have a collection something like this:

{ "_id" : "F7mdaZC2eBQDXA5wx", "quantity" : 5 }
{ "_id" : "F7mdaZC2eBQDXA5wx", "quantity" : 9 }
{ "_id" : "F7mdaZC2eBQDXA5wx", "quantity" : 34 }
{ "_id" : "F7mdaZC2eBQDXA5wx", "quantity" : 66 }

and I run query:

var selectorMin = 9;
var selectorMax = 42;

ScrapReport.find({ $and: [ { quantity: { $gte: selectorMin }, quantity: { $lte: selectorMax } } ] })

I would expect mongo to return me only 9 and 34. But for some reason it also returns 5 and 66.

What's wrong with my query?

like image 299
Villemh Avatar asked Feb 08 '23 18:02

Villemh


1 Answers

Your query is returning all the documents in that sample because it is first looking for documents whose quantity >= 9 i.e. 9, 34 and 66 AND combines that query with documents whose quantity <= 42 i.e 34, 9 and 5. It's not looking for documents within a particular range but your query explicitly looks for all documents that satisify two ranges i.e.

Documents which satisfy "quantity >= 9"
+
Documents which satisfy "quantity <= 42"

not

Documents which satisfy "9 <= quantity <= 42"

Just simplify your query to

ScrapReport.find({ "quantity": { "$gte": selectorMin, "$lte": selectorMax } })

That way, you specify a range for MongoDB to filter your documents with i.e.

9 <= quantity <= 42

Specifying a comma separated list of expressions implies an implicit AND operation and use an explicit AND with the $and operator when when the same field or operator has to be specified in multiple expressions.

like image 166
chridam Avatar answered Feb 11 '23 01:02

chridam