简体   繁体   中英

How to sort a collection by row in MongoDB?

I am using MongoDB with hapi.JS. I have a collection which contains few rows in the schema. I want to sort the rows in either asc order or desc order but want to mention it in the URI. for example the URI should look something like this

/api/v1/customers?sort=name&direction=asc&limit=30

How can I sort this collection by asc or desc order and limit can be fixed or flexible as well. I have defined like this as of now but even if I mention the sort in URI it gives the output only in asc order.

 Models.Account.find(criteria,projection,{skip:5,limit:5},function(err,resp){
                if(err)
                callbackRoute(err);
                else 
                callbackRoute(err,resp);
            }).sort({[_id]:"asc"});
db.yourcollection.find(...).sort({ name:1 }).limit(30)

or with dynamic values:

// following is ECMA 6 only
// get params and make sure values are what you expect (check for injection) + direction must be = "asc" || "desc"
db.yourcollection.find(...).sort({ [sort]: direction }).limit(30)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM