在MongoDB中对子文档进行排序 [英] Sort Sub Documents in MongoDB

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

问题描述

有没有办法在mongo查询中对子文档进行排序?

Is there a way to sort sub documents in a mongo query?

例如:

{
  "_id" : ObjectId("4c69d19532f73ad544000001"),
  "content" : "blah blah blah",
  "comments" : [
    {"author": "jim", "content":"comment content 1", "date" : "07-24-1995"},
    {"author": "joe", "content":"comment content 2", "date" : "07-24-1996"},
    {"author": "amy", "content":"comment content 3", "date" : "09-10-1999"}
  ]
}
{
  "_id" : ObjectId("4c69d19532f73ad544000002"),
  "content" : "blah blah blah",
  "comments" : [
    {"author": "jim", "content":"comment content 1", "date" : "07-24-1995"},
    {"author": "joe", "content":"comment content 2", "date" : "07-24-1996"},
    {"author": "amy", "content":"comment content 3", "date" : "07-24-1997"}
  ]
}

我希望按照我决定的方式对这些文档进行排序,然后以相反的日期顺序或我想要的其他排序方式在文档中对注释进行排序.

I want these documents to be ordered in however way I decide and then have comments ordered within my a document by reverse order of date or any other sorting I want.

mongoDB有可能吗?

Is that possible with mongoDB?

推荐答案

在mongo 2.4或更高版本中,可以在更新时使用$ sort. 新的修饰符使您可以对子文档进行排序.

In mongo version 2.4 or above, you can use $sort while updating. The new modifier let you sort sub document.

更多信息可以阅读此页, http://docs.mongodb.org/manual/reference/operator/sort/

More information could read this page, http://docs.mongodb.org/manual/reference/operator/sort/

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

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