猫鼬排序子文档和返回子文档

时间:2018-10-26 12:29:28

标签: node.js mongodb mongoose

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

2 个答案:

答案 0 :(得分:0)

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

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到达所需的输出。

答案 1 :(得分:0)

根据下面的新更新和要求,聚合是仅检索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" }
  ]
}]
相关问题