MongoDB排序 [英] MongoDB sorting

查看:54
本文介绍了MongoDB排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为主题实现突出显示"功能.主题一旦改变,它就会有一个新的"bump_date"字段.我想对它进行排序,以便当有一个"bump_date"字段时,将对其进行排序,就好像它是"created"字段一样.这是我的db.topics示例:

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)"
}

我希望排序按测试1",测试3",测试2"的顺序返回

I want the sort to return in the order of "test 1", "test 3", "test 2"

推荐答案

在MongoDB中的排序是这样的:

Sorting in MongoDB is done like so:

db.collection.find({ ... spec ... }).sort({ key: 1 })

其中1递增而-1递减.

在您的特定示例中:db.topics.find().sort({ bump_date: 1 }),尽管最好将其命名为"updated_at".

In your specific example: db.topics.find().sort({ bump_date: 1 }), although it might be better to call it something like "updated_at".

您还肯定会在"bump_date"字段上添加索引.

You'll also definitely want to put an index on your "bump_date" field.

  • sorting: http://www.mongodb.org/display/DOCS/Sorting+and+Natural+Order
  • indexes: http://www.mongodb.org/display/DOCS/Indexes

这篇关于MongoDB排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆