I want implement a “bump” feature for topics. Once a topic is bumped, it will have a new “bump_date” field. I want to sort it so that when there is a “bump_date” field, it will be sorted as if it was the “created” field. Here’s an example of my db.topics:
{
"text" : "test 1",
"created" : "Sun Nov 20 2011 02:03:28 GMT-0800 (PST)"
},
{
"text" : "test 2",
"created" : "Sun Nov 18 2011 02:03:28 GMT-0800 (PST)"
},
{
"text" : "test 3",
"created" : "Sun Nov 17 2011 02:03:28 GMT-0800 (PST)",
"bump_date: : "Sun Nov 19 2011 02:03:28 GMT-0800 (PST)"
}
I want the sort to return in the order of “test 1”, “test 3”, “test 2”
Sorting in MongoDB is done like so:
db.collection.find({ ... spec ... }).sort({ key: 1 })where
1is ascending and-1is descending.In your specific example:
db.topics.find().sort({ bump_date: 1 }), although it might be better to call it something like “updated_at”.You’ll also definitely want to put an index on your “bump_date” field.