Brian
Brian

Reputation: 944

sort mongodb collection by date in node.js

I’m new to mongodb and trying to figure out sorting with MongoClient in a node.js/express application.

This works in the mongo command line client:

db.mycollection.find().sort({"date":-1}); // displays by date, newest to oldest

I’m trying to achieve the same thing in my application:

db.collection('mycollection').find().sort({"date":-1}); //order remains the same

How can I achieve the same result as the first query? Thank you.

Upvotes: 0

Views: 1478

Answers (1)

Paul
Paul

Reputation: 36349

So, first, I'd recommend using Mongoose. Failing that, however, the Node MongoClient puts things like sorting into the find() arguments, like so:

db.collection('mycollection').find({}, {sort:{date:-1}});

Upvotes: 2

Related Questions