Dupont
Dupont

Reputation: 403

mongodb - $sort child documents only

When i do a find all in a mongodb collection, i want to get maintenanceList sorted by older maintenanceDate to newest.

The sort of maintenanceDate should not affect parents order in a find all query

{
   "_id":"507f191e810c19729de860ea",
   "color":"black",
   "brand":"brandy",
   "prixVenteUnitaire":200.5,
   "maintenanceList":[
      {
         "cost":100.40,
         "maintenanceDate":"2017-02-07T00:00:00.000+0000"
      },
      {
         "cost":4000.40,
         "maintenanceDate":"2019-08-07T00:00:00.000+0000"
      },
      {
         "cost":300.80,
         "maintenanceDate":"2018-08-07T00:00:00.000+0000"
      }
   ]
}

Any guess how to do that ? Thank you

Upvotes: 0

Views: 55

Answers (1)

MilanRegmi
MilanRegmi

Reputation: 519

Whatever order the fields are in with the previous pipeline stage, as operations like $project and $group effectively "copy" same position.So, it will not change the order of your fields in your aggregated result.

And the sort of maintenanceDate through aggregation will not affect parents order in a find all query. So, simply doing this should work.

Assuming my collection name is example.

 db.example.aggregate([
  {
    "$unwind": "$maintenanceList"
  },
  {
    "$sort": {
      "_id": 1,
      "maintenanceList.maintenanceDate": 1
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "color": {
        $first: "$color"
      },
      "brand": {
        $first: "$brand"
      },
      "prixVenteUnitaire": {
        $first: "$prixVenteUnitaire"
      },
      "maintenanceList": {
        "$push": "$maintenanceList"
      }
    }
  }
])

Output: enter image description here

Upvotes: 1

Related Questions