【问题标题】:mongoose sorting sub document and return sub document猫鼬排序子文档并返回子文档
【发布时间】:2018-10-30 16:16:41
【问题描述】:

persons收藏:

{ 
    name: "jhon",
    msgs: {
        chat_one: [
            {id: 1234, msg: "hi", date: "18/05/2018"},
            {id: 1234, msg: "hello", date: "19/05/2018"}
        ],
        chat_two: [
            {id: 1234, msg: "hi", date: "18/05/2018"},
            {id: 1234, msg: "hello", date: "19/05/2018"}
        ]
    }
}

如何使用猫鼬查询并获取如下数据。

  • 按日期排序。
  • 并返回一个人的chat_one 消息。
{
  chat_one: [
    {id: 1234, msg: "hello", date: "19/05/2018"},
    {id: 1234, msg: "hi", date: "18/05/2018"}
  ]
}

【问题讨论】:

  • 日期存储为字符串?
  • 不是日期对象

标签: node.js mongodb mongoose


【解决方案1】:

根据您的新更新和以下要求,聚合仅检索 chat_one 消息。

db.collection.aggregate([
  { $match: { name: "jhon" }},
  { $unwind: "$msgs.chat_one" },
  { $sort: { "msgs.chat_one.date": -1 }},
  { $group: { _id: "$name", chat: { $push: "$msgs.chat_one" }}},
  { $project: { _id: 0 }} // To remove `_id`
])

输出:

[{
  "chat": [
    { "date": "19/05/2018", "id": 1234, "msg": "hello" },
    { "date": "18/05/2018", "id": 1234, "msg": "hi" }
  ]
}]

【讨论】:

    【解决方案2】:

    一种方法是通过这样的聚合:

    db.collection.aggregate([
      { $match: { name: "jhon" }},
      { $unwind: "$msgs" },
      { $sort: { "msgs.date": -1 }},
      { $group: { _id: "$name", msgs: { $addToSet: "$msgs" }}},
      { $project: { _id: 0 }}
    ])
    

    你可以看到working here

    我们的想法是先$match 在名称上然后$unwind 这样我们就可以在日期上$sort 然后$group$project 来获得所需的输出。

    【讨论】:

    • 感谢您的解决方案。其实我的要求不一样。请检查问题刚刚我已经更新了。
    猜你喜欢
    • 2015-10-01
    • 2016-08-17
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 2017-05-07
    • 2015-06-26
    • 2018-06-01
    • 2019-05-31
    相关资源
    最近更新 更多