如何从 MongoDB 文档中的对象 return 排序数组?

How to return sorted array from object from MongoDB document?

我想要 return 一个数组,它是我的 mongo model/document 中的一个 属性,并且我希望对该数组进行排序。我的 MongoDB 文件看起来像:

_id: ObjectID("6248e49c88ff07aedee8c000")
title: "School"
items: [
{
   sort: 2,
   name: "homework"
},
{
   sort: 1,
   name: "exam"
},
{
   sort: 3,
   name: "essay"
},

]

我正在尝试 return

items: [
{
   sort: 1,
   name: "exam"
},
{
   sort: 2,
   name: "homework"
},
{
   sort: 3,
   name: "essay"
}

]

我试过聚合:

 app.get("/api/v1/lists/:id", async (req,res) =>{

    List.aggregate([{
        "$match" :{"_id": req.params.id}
    },{
        "$unwind" : "$items"
    } , {
        "$sort" : {"sort": 1}
    }
    ], (err, items)=>{
        res.json(items)
    })
}

Mongo Playground reference 由于 $unwind returns 数组作为对象,我们使用 $group 将对象推回项目数组

   db.collection.aggregate([
  {
    $unwind: "$items"
  },
  {
    $sort: {
      "items.sort": 1
    }
  },
  {
    $group: {
      _id: "$_id",
      items: {
        $push: "$items"
      }
    }
  },
  
])

输出-

[
  {
    "_id": 1.212112e+06,
    "items": [
      {
        "name": "exam",
        "sort": 1
      },
      {
        "name": "homework",
        "sort": 2
      },
      {
        "name": "essay",
        "sort": 3
      }
    ]
  }
]