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?
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.
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.
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.
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.
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) {})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With