Home > Net >  How to return sorted array from object from MongoDB document?
How to return sorted array from object from MongoDB document?

Time:04-04

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

CodePudding user response:

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
      }
    ]
  }
]
  • Related