简体   繁体   English

按 mongoose 中的孩子对文档进行排序

[英]sort documents by their children in mongoose

I have a mongodb collection as follows:我有一个 mongodb 集合如下:

[
  {
    "_id": { "$oid": "609b8f06a28f6728d19b486d" },
    "user1": "609952c2b112741634d27d89",
    "user2": "609b8202b5a389099cae3ce6",
    "messages": [
      {
        "body": "Hello user 2",
        "user": "609952c2b112741634d27d89",
        "readed": true,
        "created": { "$date": "2021-05-13T01:38:07.502Z" }
      },
      {
        "body": "How old are you?",
        "user": "609952c2b112741634d27d89",
        "readed": false,
        "created": "2021-05-13T01:40:07.502Z"
      },
      {
        "body": "I am fine. Are you ready?",
        "user": "609b8202b5a389099cae3ce6",
        "readed": false,
        "created": "2021-05-13T01:42:07.502Z"
      },
      {
        "body": "Yes. Lighgui start",
        "user": "609952c2b112741634d27d89",
        "readed": false,
        "created": "2021-05-13T01:38:50.502Z"
      }
    ]
  }
]

I want to sort chats that have messages up first how do I do that?我想先对有messages的聊天进行排序,我该怎么做?

also if possible i would like to get the latest message of each chat and the number of messages with readed=false如果可能的话,我想获取每个聊天的最新消息以及readed=false的消息数量

You can use您可以使用

  • $unwind to destructure the array $unwind解构数组
  • $sort to sort the array based on created of messages $sort根据创建的消息对数组进行排序
  • $group to restructure the array $group重组数组

Here is the code这是代码

db.collection.aggregate([
  {
    $unwind: {
      path: "$messages",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    "$sort": {"messages.created": 1 }
  },
  {
    "$group": {
      "_id": "$_id",
      user1: { $first: "$user1" },
      user2: { $first: "$user2" },
      "messages": { "$push": "$messages" }
    }
  }
])

Working Mongo playground工作Mongo游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM