开发者

Speed up a MongoDB find() with better sorting? (using mongoose orm)

开发者 https://www.devze.com 2023-02-25 12:00 出处:网络
Right now I have something like this.... Item.开发者_运维技巧find({}, function (docs) { for (var i = docs.length-15; i < docs.length; i++){

Right now I have something like this....

Item.开发者_运维技巧find({}, function (docs) {
    for (var i = docs.length-15; i < docs.length; i++){
     client.send(JSON.stringify(docs[i]));
    }                   
});

but it seems to be very slow. I'm hoping to speed it up by doing something like...

Item.find().sort({_id:-1}).limit(15)...?

Is this possible? Will it help?

Thanks!


If you are only interested in the first (or last as in the case of sorting with _id: -1) 15 documents then yes, setting a limit on the query is a very good idea. Limiting on the client side as in your first example means that the database sends every single document to the client, and then the client ignores every but the last 15.

However, the Mongoose syntax for specifying a limit is different from the Mongo shell syntax, here what I think you want:

Item.find().sort([['_id','descending']]).limit(15).each(function(doc) {
  client.send(JSON.stringify(doc));
});

If I'm not mistaken you can chain a number of actions on a Mongoose query, and then call each to send it and get each document of the result passed to your callback.


From what I can gleam from the actual source code and tests, since mongoose 1.0.14 the sort() parameter has changed slightly to no longer accept an array. Furthermore, you seem to need to call find() again on the actual Query object which is returned on the find call (plus watching out for your err object). So:-

  Item.find().sort('_id','descending').limit(15).find(function(err, doc) {
    client.send(JSON.stringify(doc));
  });

Hopefully might do what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消