首页 > 解决方案 > 按他们的孩子在猫鼬中排序文件

问题描述

我有一个 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"
      }
    ]
  }
]

我想对messages首先出现的聊天进行排序,我该怎么做?

如果可能的话,我想获取每个聊天的最新消息以及与readed=false

标签: javascriptnode.jsmongodbmongoosemongodb-query

解决方案


您可以使用

  • $unwind解构数组
  • $sort根据创建的消息对数组进行排序
  • $group重构数组

这是代码

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

工作Mongo游乐场


推荐阅读