1

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?

3 Answers 3

3

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'}) 
Sign up to request clarification or add additional context in comments.

Comments

0

I did it.

With the $and operator.

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

Comments

0

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']}})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.