Sort query results based desc value of nested subdocument within array Mongoose/Mongodb

We can’t sort array directly, But aggregation helps it

  • $unwind helps to de-structure the array
  • $sort helps to sort as you wish
  • $group helps to re-group the de-structured array

Mongo script is given below

db.collection.aggregate([
  {
    "$match": {
      "serviceAreas.slug": "nashville"
    }
  },
  {
    $unwind: "$serviceAreas"
  },
  {
    $sort: {
      "serviceAreas.totalClosedSales": -1
    }
  },
  {
    $addFields: {
      total: "$serviceAreas.totalClosedSales"
    }
  },
  {
    $sort: {
      total: -1
    }
  },
  {
    $group: {
      _id: "$_id",
      mlsId: {
        $first: "$mlsId"
      },
      firstName: {
        $first: "$firstName"
      },
      lastName: {
        $first: "$lastName"
      },
      slug: {
        $first: "$slug"
      },
      serviceAreas: {
        $push: "$serviceAreas"
      }
    }
  }
])

Working Mongo playground

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top