mongoose 从嵌套数组排序MongoDB

gjmwrych  于 2023-10-19  发布在  Go
关注(0)|答案(1)|浏览(129)

我正在使用mongoose来处理我的数据。到目前为止,我在这里得到了这个

const personal = await culvertSchema.aggregate([
      { $match: { "characters.name": selectedCharacter } },
      { $unwind: "$characters" },
      { $sort: { "characters.scores.score": -1 } },
      { $limit: 1 },
    ]);

但它似乎并不适用于对“分数”进行排序。或者我甚至没有正确地访问它们。我不确定.我怎样才能对给定角色名的分数进行排序?
这是我的结构:

{
  "_id": "336277029060345856",
  "characters": [
    {
      "name": "druu",
      "scores": [
        {
          "date": "09/03/23",
          "score": 41
        },
        {
          "date": "09/03/23",
          "score": 12
        },
        {
          "date": "09/03/23",
          "score": 52
        },
        {
          "date": "09/03/23",
          "score": 100
        }
      ]
    },
    {
      "name": "druuwu",
      "scores": []
    }
  ]
}

谢谢你,谢谢

vq8itlhq

vq8itlhq1#

在当前$unwind之后执行$sortArray

db.collection.aggregate([
  {
    "$unwind": "$characters"
  },
  {
    "$match": {
      "characters.name": "druu"
    }
  },
  {
    "$set": {
      "characters.scores": {
        "$sortArray": {
          "input": "$characters.scores",
          "sortBy": {
            "score": -1
          }
        }
      }
    }
  }
])

Mongo Playground

相关问题