Skip to content
Advertisement

How to return sorted array from object from MongoDB document?

I want to return an array, which is a property inside my mongo model/document, and I want that array to be sorted.

My MongoDB document looks like:

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

]

And I’m trying to return:

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

]

I have tried aggregation:

 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)
    })
}

Advertisement

Answer

Mongo Playground reference Since $unwind returns the arrays as objects, we are using the $group to push the objects back into the items array

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

Output –

[
  {
    "_id": 1.212112e+06,
    "items": [
      {
        "name": "exam",
        "sort": 1
      },
      {
        "name": "homework",
        "sort": 2
      },
      {
        "name": "essay",
        "sort": 3
      }
    ]
  }
]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement