8

Note: I have seen the other question and tried answers from it with no luck.

I have a collection in MongoDB:

{ _id: 1, category_id: 1, time_added: 1234567890, name: "abc" }

I need to find last 10 entries from category_id equal to 10. Sound simple?

collection.find({ 'category_id': 10 }, {}, { _id: -1, limit : 10}, function (e, d) {});

But running this gives me first 10 records instead of last 10. Looks like driver has priority to "limit" and not "sorting"... I also tries with $natural and sorting on time_added. Whenever I run the same query from command line - I get what I need. Here is what I type into command line:

collection.find({ 'category_id': 10 }).sort({_id: -1}).limit(10)

What am I doing wrong? Is there an alternative way to do this with node.js?

3
  • 1
    Are you using the node-mongodb-native driver? It has support for a chainable sort method, allowing you to issue a query to the driver very much like your command line. Commented Nov 29, 2013 at 23:25
  • @RayToal Yes. I am using that driver. Where do I put the callback? In limit as the last parameter? What if I remove .limit(), can I place callback in any function as a last parameter? P.S. I tried and it worked. Add that as an answer, so that I can accept it. Commented Nov 29, 2013 at 23:34
  • @Xeos - you can add an answer and mark it as answered. Commented Nov 30, 2013 at 1:24

1 Answer 1

7

Turns out node.js accepts function calls in the same way the command line interface does. Every function has last optional argument as callback function. So this code runs and returns the correct results:

collection.find({ 'category_id': 10 }).sort({_id: -1}).limit(10, function (e, d) {})
Sign up to request clarification or add additional context in comments.

1 Comment

@G.Ghez It's not random at all. Here is the description of the ObjectId docs.mongodb.org/manual/reference/object-id When I sort by ObjectId, I am essentially sorting it by timestamp. Further, if there were multiple inserts in one second, then there is the counter. This works pretty well for one-server setup. It would not work with multiple servers, as machine and process IDs would mess with the chronological ordering.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.