Easiest way to sort an array in MongoDB

MongoDBDatabaseBig Data Analytics

The easiest way to sort an array in MongoDB, use $sort. Let us create a collection with documents −

> db.demo242.insertOne(
...
...   {"details2":
...      [
...         {"ShipingDate":new ISODate("2019-10-11"),"Price":1400},
...         {"ShipingDate":new ISODate("2019-10-01"),"Price":1600 }
...      ]
...   }
...
...);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4429229af932883c61ea44")
}

Display all documents from a collection with the help of find() method −

> db.demo242.find();

This will produce the following output −

{
   "_id" : ObjectId("5e4429229af932883c61ea44"), "details2" : [
      { "ShipingDate" : ISODate("2019-10-11T00:00:00Z"), "Price" : 1400 },
      { "ShipingDate" : ISODate("2019-10-01T00:00:00Z"), "Price" : 1600 }
   ] 
}

Following is the query to sort an array in MongoDB −

> db.demo242.aggregate([ {$unwind: "$details2"}, {$sort: {"details2.ShipingDate":1}}, {$group: {_id:"$_id", details2: {$push:"$details2.ShipingDate"}}} ]);

This will produce the following output −

{ "_id" : ObjectId("5e4429229af932883c61ea44"), "details2" : [ ISODate("2019-10-01T00:00:00Z"), ISODate("2019-10-11T00:00:00Z") ] }
raja
Published on 30-Mar-2020 17:10:14
Advertisements