从集合中选择并排序所有子文档

时间:2014-03-23 19:45:19

标签: mongodb aggregation-framework nosql

我在一个集合中有以下文件:

{
  "thread_object": "Sed consectetur, massa id aliquam lacinia",
  "thread_comments": [
    {
      "comment_date": "11/01/2014 17:23:19",
      "comment_user": "Integer",
      "comment_content": "In suscipit enim at eleifend auctor"
    },
    {
      "comment_date": "12/01/2014 17:23:19",
      "comment_user": "Suspendisse",
      "comment_content": "Quisque facilisis magna pellentesque diam mollis"
    }
  ]
},
{
  "thread_object": "Vivamus auctor mauris augue",
  "thread_comments": []
},
{
  "thread_object": "Phasellus volutpat, sem id convallis elementum",
  "thread_comments": [
    {
      "comment_date": "10/01/2014 17:23:19",
      "comment_user": "Donec",
      "comment_content": "Suspendisse a pellentesque justo"
    }
  ]
}

如何检索所有评论的有序列表?

{
  "comment_date": "10/01/2014 17:23:19",
  "comment_user": "Donec",
  "comment_content": "Suspendisse a pellentesque justo"
},
{
  "comment_date": "11/01/2014 17:23:19",
  "comment_user": "Integer",
  "comment_content": "In suscipit enim at eleifend auctor"
},
{
  "comment_date": "12/01/2014 17:23:19",
  "comment_user": "Suspendisse",
  "comment_content": "Quisque facilisis magna pellentesque diam mollis"
},

1 个答案:

答案 0 :(得分:0)

您可以使用aggregation framework unwind thread_comments数组,然后按comment_date排序。但是,因为日期存储为字符串,如果按comment_date排序,结果将不会被排序。您可能希望使用javascript将comment_date转换为Date()。这是example。关于SO也有其他类似的问题。

假设您已将comment_date转换为Date(),则下面的查询将起作用:

db.collection.aggregate([
    {$unwind:"$thread_comments"},
    {$sort:{"thread_comments.comment_date":-1}}
])