RMontes13
RMontes13

Reputation: 2148

How to query with $in with multiple arrays

I´m developing a filter system that you can filter a set of tv´s by price, brand and screen size. Now, I´m able to filter the tv´s by brand like follows:

db.tvs.find({brand: {$in: ['LG', 'Samsung']}}) 

And it works.

But right now, I´d like to do the same but with multiple filters (price and screensize), something like this:

db.tvs.find({brand: {$in: ['LG', 'Samsung']}}, {screensize: {$in: ['37', '42']}}) 

It is possible?

Upvotes: 1

Views: 46

Answers (3)

Amol M Kulkarni
Amol M Kulkarni

Reputation: 21639

You should look into what is happening with you code:

db.tvs.find( { brand: { $in: ['LG', 'Samsung']} } , { screensize: { $in: ['37', '42']}} )

The query you put is some thing like db.collectionName.find({},{});
Check this docs, It clearly says db.collection.find({<criteria>}, {<projection>}). So your query should be constructed such that it should belong to the first parameter not the <projection>.

In your case as mentioned above, the second query you wanted to make is going as second parameter which is intrepreted as for projection.
The projection parameter specifies which fields to return.
Projection parameter should be constructed as follows:
{'FieldName':1}
Where, 1 for the field to be returned in result otherwise 0 to explicitly excluded.

So coming to the answer you are looking for is as below:
db.tvs.find({brand:{$in: ['LG', 'Samsung']}, screensize: {$in: ['37', '42']}})

Upvotes: 0

Makis Tsantekidis
Makis Tsantekidis

Reputation: 2738

You didn't have to use $and... You could do it like this:

db.tvs.find({brand: {$in: ['LG', 'Samsung']}, screensize: {$in: ['37', '42']}})

The only difference with

with your version

db.tvs.find({brand: {$in: ['LG', 'Samsung']}}, {screensize: {$in: ['37', '42']}})

is that i did not close the first brackets {} after the brand and didn't open a new one before screensize. You need to have them all in the same bson object

A more simple case to understand is this:

db.tvs.find( {brand : "LG" , screensize : '37'}) 

Upvotes: 3

RMontes13
RMontes13

Reputation: 2148

I did it.

With the $and operator.

db.tvs.find({ $and: [ { brand: {$in: ["LG", "Samsung"]} },{ size: {$in: ["37"] }}, { price: { $gte: 0 }  }, { price: { $lte: 499 } } ] })

Upvotes: 0

Related Questions