【问题标题】:How to sort nested field in mongodb / mongoose如何在 mongodb / mongoose 中对嵌套字段进行排序
【发布时间】:2020-04-13 15:46:52
【问题描述】:

我正在尝试按日期对 cme​​ts 进行排序,但我无法正确操作。

   {
        "_id": "5defc10b8e753623b4ad0adf",
        "title": "bla bla",
        "owner:"idToPopulate",
        "comments": [
            {
                "_id": "5dfc2185e62103121cfc0f18",
                "reply": "1",
                "replyDate": "2019-12-10T16:00:11.228Z"
            },
            {
                "_id": "5dfc218be62103121cfc0f19",
                "reply": "2",
                "replyDate": "2019-13-10T16:00:11.228Z"
            }
        ]
    }

这是我尝试过的方式(结果必须是,按上次日期对 cme​​ts 进行排序

.sort({"comments.replyDate":1})

【问题讨论】:

  • 你为什么不试试 '1' 而不是 '-1' 呢?我认为-1 表示升序(对于 1 然后 2 正确)
  • 嗨 @CeliusStingher 我的错误(输入错误),但它也不起作用
  • 您必须使用聚合来对数组中的子文档进行排序 - 按子文档的字段排序。在这篇文章中查看聚合的答案:How to sort sub-documents in the array field?

标签: mongodb mongoose-schema


【解决方案1】:

使用$sort 您可以对数据进行排序,但在使用之前您必须拆分数组。试试这个 mongo 查询:

 db.collection.aggregate([
  {
    $unwind: {
      path: "$comments"
    }
  },
  {
    $sort: {
      "comments.replyDate": -1
    }
  },
  {
    $group: {
      _id: "$_id",
      comments: {
        $push: {
          _id: "$comments._id",
          item: "$comments.reply",
          date: "$comments.replyDate"
        }
      }
    }
  }
])

【讨论】:

  • 对不起,但它不起作用,我的意思是,不检索结果(甚至省略 serverResponse)
  • @AlexHunter 根据您编辑的集合数据更新查询
  • 现在可以了!,该对象中的最后一件事,在 cmets 对象数组之外,我有更多信息,我该如何显示它?
  • 只需将 $group 阶段中的值分组为:_id: { _id: "$_id", example_data: "$example_data" } 并添加一个阶段 $project 以收集所有必需的值跨度>
  • 我试过了,它显示了,但是,它改变了对象顺序,我用数据更新了我的帖子,顺便说一下一些字段也需要填充
猜你喜欢
  • 2020-02-06
  • 1970-01-01
  • 2020-04-29
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2021-11-01
  • 2016-06-28
相关资源
最近更新 更多