Format date value in MongoDB shell?

MongoDBDatabaseBig Data Analytics

To format date value, use $dateToString in MongoDB. Let us create a collection with documents −

> db.demo480.insertOne({id:1,"DueDate":new ISODate("2020-01-10")});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e821056b0f3fa88e2279098")
}
> db.demo480.insertOne({id:1,"DueDate":new ISODate("2017-12-21")});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e821062b0f3fa88e2279099")
}
> db.demo480.insertOne({id:1,"DueDate":new ISODate("2019-10-12")});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e82106ab0f3fa88e227909a")
}
> db.demo480.insertOne({id:1,"DueDate":new ISODate("2019-12-01")});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e821078b0f3fa88e227909b")
}

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

> db.demo480.find();

This will produce the following output −

{ "_id" : ObjectId("5e821056b0f3fa88e2279098"), "id" : 1, "DueDate" : ISODate("2020-01-
10T00:00:00Z") }
{ "_id" : ObjectId("5e821062b0f3fa88e2279099"), "id" : 1, "DueDate" : ISODate("2017-12-
21T00:00:00Z") }
{ "_id" : ObjectId("5e82106ab0f3fa88e227909a"), "id" : 1, "DueDate" : ISODate("2019-10-
12T00:00:00Z") }
{ "_id" : ObjectId("5e821078b0f3fa88e227909b"), "id" : 1, "DueDate" : ISODate("2019-12-
01T00:00:00Z") }

Following is the query to format date value in MongoDB shell −

> db.demo480.aggregate([
...    { "$match": { "id" : 1 } },
...    { "$sort": { "DueDate": -1 } },
...    {
...       "$project": {
...          "_id": 0,
...          "DueDate": {
...             "$dateToString": {
...                "format": "%Y-%m-%d %H-%M",
...                "date": "$DueDate"
...             }
...          }
...       }
...    }
... ])

This will produce the following output −

{ "DueDate" : "2020-01-10 00-00" }
{ "DueDate" : "2019-12-01 00-00" }
{ "DueDate" : "2019-10-12 00-00" }
{ "DueDate" : "2017-12-21 00-00" }
raja
Published on 11-May-2020 13:22:37
Advertisements