Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.JS + Monk. "ORDER BY" in "find"

It is necessary to make a selection on a certain condition, and sort the result on the previously mentioned field. How to do it?

As a driver for MongoDB using "Monk".

like image 306
RomanGor Avatar asked Dec 21 '22 02:12

RomanGor


1 Answers

Assuming you have already got as far as getting a collection, then what you need is the find() method:

collection.find(query, options, callback);

You can use the query object to specify conditions, and the options object to sort. For detail on how to build the two objects see the mongodb native driver documentation.

So in your case specifically, something like this example might work. For the "condition" you mention, I'm using the condition that the "quantity" field is greater than 0, then sorting by quantity, largest first.

collection.find(
    {quantity: {$gt: 0}},
    {sort: {quantity: -1}},
    function(err, docs) {
        // docs is the sorted array of your results, process them here
    });

Monk itself is fairly lightly documented, but it mostly calls through to mongoskin and then the native mongodb driver linked above, so the documentation for those is a good place to look.

like image 86
swilson Avatar answered Jan 13 '23 15:01

swilson