【问题标题】:Select and order all subdocuments from a collection从集合中选择并排序所有子文档
【发布时间】:2014-05-01 00:40:03
【问题描述】:

我的集合中有以下文档:

{
  "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"
    }
  ]
}

如何检索所有 cmets 的有序列表?

{
  "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"
},

【问题讨论】:

    标签: mongodb aggregation-framework nosql


    【解决方案1】:

    您可以使用aggregation frameworkunwind 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}}
    ])
    

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 2019-09-28
      • 2018-07-20
      • 2021-10-30
      • 2018-06-15
      • 2019-11-03
      • 2021-11-15
      • 1970-01-01
      • 2023-01-27
      相关资源
      最近更新 更多