Rob van Dijk
Rob van Dijk

Reputation: 722

Mongo query by and sort by date?

I have the following query:

let inputDate = new Date(new Date().toISOString()) //OR new Date() which doesn't work either
let found = Collection.find({
        $query: {
            storedAt: {
                $lte: inputDate
            }
        },
        $orderBy: { //doesn't work for some reason
            storedAt: -1
        }
}).fetch()

I'm trying to get the returned query to be sorted by date, with the most recent date up top (so closest to the time the function is called) However, no matter what I order by, -1 or 1, the order is still wrong, as it starts with the oldest date. My dates are correctly stored in the database in ISODate format, I've checked. I've also tried running this query with just inputDate = new Date() but this isn't working either.

Upvotes: 0

Views: 2860

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21364

You seem to think that Meteor collection queries are the same as MongoDB queries, but they are not. Their syntax is quite different. Please see the documentation for find: https://docs.meteor.com/api/collections.html#Mongo-Collection-find

In your case, what you probably are looking for is:

let found = Collection.find({storedAt: {$lte: inputDate}},
                            {sort: {storedAt: -1}}).fetch()

Upvotes: 2

Related Questions