人员
集合:
{
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"}
]
}
}
如何使用 mongoose 查询并获取如下数据。
- 按日期排序。
- 并返回单个人的
chat_one
条消息。
{ chat_one: [ {id: 1234, msg: "hello", date: "19/05/2018"}, {id: 1234, msg: "hi", date: "18/05/2018"} ] }
最佳答案
根据您的新更新和要求,下面是仅检索 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" }
]
}]
关于node.js - mongoose排序子文档并返回子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53008785/