Search code examples
mongodbaggregation-frameworkmongodb-.net-driver

MongoDB - Sort result and Convert date to string


I have a requirement where the result should be sort by DESC(by date) order, so latest document will be first and followed by other documents and convert date to string format like "2019-06-27" this.

I can convert date to string format by this $dateToString function and but can't sort as it is now in string format. However, tried to apply the first sort and then convert but not getting the expected output.

Below are documents stored in MongoDB collection :

{ "_id": "9d78d0e8-7b13-4487-88a3-d91d64f29b38", "Number": "001", "createdon": { "$date": "2019-09-19T00:00:00.000Z" } }, { "_id": "5d78d0e8-7b13-4487-88a3-d91d64f29b02", "Number": "002", "createdon": { "$date": "2019-09-13T00:00:00.000Z" } }, { "_id": "2w78d0e8-7b13-4487-88a3-d91d64f29b47", "Number": "003", "createdon": { "$date": "2019-09-25T00:00:00.000Z" } }, { "_id": "6e78d0e8-7b13-4487-88a3-d91d64f29b2d", "Number": "004", "createdon": { "$date": "2020-01-18T00:00:00.000Z" } }

Expected Result:

{ "_id": "6e78d0e8-7b13-4487-88a3-d91d64f29b2d", "Number": "004", "createdon": "2020-01-18" }, { "_id": "2w78d0e8-7b13-4487-88a3-d91d64f29b47", "Number": "003", "createdon": "2019-09-25" }, { "_id": "9d78d0e8-7b13-4487-88a3-d91d64f29b38", "Number": "001", "createdon": "2019-09-19" }, { "_id": "5d78d0e8-7b13-4487-88a3-d91d64f29b02", "Number": "002", "createdon": "2019-09-13" }

Any help would be appreciate!! Thanks.


Solution

  • However, tried to apply the first sort and then convert but not getting the expected output.

    What was the problem. This aggregation perfectly works for me :

    db.collection.aggregate([
      {
        $sort: {
          createdon: -1
        }
      },
      {
        $addFields: {
          createdon: {
            $dateToString: {
              date: "$createdon",
              format: "%Y-%m-%d"
            }
          }
        }
      }
    ])
    

    You can try it here.