alexandernst
alexandernst

Reputation: 15089

Saving and sorting dates in MongoDB

I'm saving a date in a document the following way (NodeJS and Javascript driver for MongoDB):

my_data: {
    my_date: new Date()
}
db.collection("my_test_collection").save(my_data, {w: 0});

When I query the data from my_test_collection I see that my_date is actually a String and it looks like: 2013-09-23T10:46:01.914Z

  1. Does this matter?
  2. How do I sort my query by this field?

I tried ....find().sort(['my_date', 'asc']) but this doesn't seem to work.

Upvotes: 0

Views: 3259

Answers (1)

thtsigma
thtsigma

Reputation: 4938

It shouldn't matter that its returning the date to you like that.

You should be able to sort through it like so:

db.my_test_collection.find().sort({'my_date':1})pe

If you wish to sort by descending simply change the 1 to -1 like so:

db.my_test_collection.find().sort({'my_date':-1})

Hope this helps.

Upvotes: 3

Related Questions