Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do more advance queries with Mongoose? Specifically a query using $or

I was learning some mongodb stuff, and it's pretty awesome!

I decided to try it out with mongoose in node and came upon the realization that I have no idea how to run an or command, so I looked up how you would do an or command in regular mongoose and found that the query is similar to this:

db.meh.find({ $or : [ { a : 3 }, { b : 4 } ] });

And that seems to work great with the command line program for finding all entities where a == 3 or b == 4

But... How would I do this in mongoose?

Any help is appreciated!!

Note I also would like to be able to do this with the findOne() method, but I'm assuming that it'll act just the same as find() with a limit on it

like image 947
DanZimm Avatar asked Nov 05 '11 03:11

DanZimm


2 Answers

It should be the same in mongoose.

SomeObjects.find({$or : [{a: 3}, {b: 4}]});

Note I also would like to be able to do this with the findOne() method, but I'm assuming that it'll act just the same as find() with a limit on it

Yea, that should work as well.

like image 151
Chance Avatar answered Oct 18 '22 22:10

Chance


i don't think you need to find anything here as mongoose has helpers for that (not sure if this was the case at the time of the post though):

query.or([{ color: 'blue' }, { color: 'red' }]);

mongoose query doc

like image 39
ag4ve Avatar answered Oct 19 '22 00:10

ag4ve