Reputation: 409
When you do a mongodb query, you normally get the results in descending order of age(old to new). How can I get it in the ascending order?
I know that I can save the createdAt timestamp and do a
.sort({createdAt:-1})
on the query to do this, but saving the cretedAt timestamp seperately when the information is already present in _id seems like overkill.
Is there a way to get the results in the ascending order of age (new to old) without using a createdAt timestamp?
Upvotes: 1
Views: 1715
Reputation: 11
timestamp is already stored in _id
field. So if you want to sort documents from new to old. You can do it in the following way -
sort({_id:-1})
Upvotes: 1
Reputation: 425
If you are referring to the natural order which reflects insertion order of documents.
Consider the following query :
db.trees.insert( { _id: 1, name: "oak"} )
db.trees.insert( { _id: 2, name: "chestnut"} )
db.trees.insert( { _id: 3, name: "maple"} )
db.trees.insert( { _id: 4, name: "birch"} )
The following query returns the documents in the natural order :
db.trees.find().sort( { $natural: 1 } )
[
{ "_id" : 1, "name" : "oak"}
{ "_id" : 2, "name" : "chestnut"}
{ "_id" : 3, "name" : "maple"}
{ "_id" : 4, "name" : "birch"}
]
However remove operations free up space which are then taken up by newly inserted documents then, natural order of documents will not reflect insertion order.
Upvotes: 0