Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoDB "multiple" select

Tags:

mongodb

I am not exactly sure on how this can be called, but what I want to do is select two different values with a limit; for example select 5 documents with of type "A", and 5 of type "B"; something like:

db.students.find({class: 'A'}).limit(10);
db.students.find({class: 'B'}).limit(10);

can this be done with only ONE query? Thanks in advance.

like image 950
john smith Avatar asked Feb 23 '26 17:02

john smith


2 Answers

You could use $in to achieve this

db.students.find({class: {$in: ['A', 'B'] }}).limit(10)

This is not the same output.

db.students.find({class: {$in: ['A', 'B'] }}).limit(10)

This will limit the Results of Class A and B to 10.

Hence, for example class A matches 10 Students and class B matches 10 Students. The result would be 10 Students.

While this one:

db.students.find({class: 'A'}).limit(10);
db.students.find({class: 'B'}).limit(10);

Will give 20 Students

like image 22
Mark Jezreel C. Dagot Avatar answered Feb 26 '26 09:02

Mark Jezreel C. Dagot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!