Convert Field Value to DateTime Day of Month in MongoDB Query



To convert filed value to create datetime day of month, use MongoDB aggregate(). Let us create a collection with documents −

> db.demo209.insertOne(
...   {
...      "_id" : "101",
...      "details" : [
...         {
...            "dat" : 1528929908,
...            "Name" : "Chris"
...         },
...         {
...            "dat" : 1529082069,
...            "Name":"Carol"
...         }
...      ],
...      "Age" : 25,
...      "CountryName" : "US"
...   }
...);
{ "acknowledged" : true, "insertedId" : "101" }

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

> db.demo209.find().pretty();

This will produce the following output −

{
   "_id" : "101",
   "details" : [
      {
         "dat" : 1528929908,
         "Name" : "Chris"
      },
      {
         "dat" : 1529082069,
         "Name" : "Carol"
      }
   ],
   "Age" : 25,
   "CountryName" : "US"
}

Following is the query to convert the field value and create datetime day of month during projection −

> db.demo209.aggregate({
...   "$unwind": "$details"
...   }, {
...         "$project": {
...            "Age": 1,
...            "CountryName": 1,
...            "Name": "$details.Name",
...            "DayOfMonth": {
...               "$dayOfMonth": {
...                  "$add": [new Date(0), {
...                     "$multiply": ["$details.dat", 1000]
...               }]
...            }
...         }
...   }
...})

This will produce the following output −

{ "_id" : "101", "Age" : 25, "CountryName" : "US", "Name" : "Chris", "DayOfMonth" : 13 }
{ "_id" : "101", "Age" : 25, "CountryName" : "US", "Name" : "Carol", "DayOfMonth" : 15 }
Updated on: 2020-03-27T10:58:16+05:30

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements