Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select last N records from MongoDB using node.js

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?

like image 890
Xeos Avatar asked Nov 29 '13 23:11

Xeos


People also ask

How to get the last N Records in MongoDB?

To get the last N records in MongoDB, you need to use limit (). The syntax is as follows: To understand the above syntax, let us create a collection with document.

How do I find data in MongoDB node Node JS?

Node.js MongoDB Find. In MongoDB we use the find and findOne methods to find data in a collection. Just like the SELECT statement is used to find data in a table in a MySQL database.

How to query multiple documents in a collection in MongoDB?

You can query for multiple documents in a collection with collection.find (). The find () method uses a query document that you provide to match the subset of the documents in the collection that match the query. If you don't provide a query document (or if you provide an empty document), MongoDB returns all documents in the collection.

How does the FIND() METHOD work in MongoDB?

The find () method uses a query document that you provide to match the subset of the documents in the collection that match the query. If you don't provide a query document (or if you provide an empty document), MongoDB returns all documents in the collection. For more information on querying MongoDB, see our documentation on query documents.


1 Answers

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) {})
like image 114
Xeos Avatar answered Sep 19 '22 16:09

Xeos