MongoDB query to convert the field value and create datetime day of month during projection?

To convert a field value and create datetime day of month during projection in MongoDB, use aggregate() with $unwind to flatten arrays and $dayOfMonth to extract the day from converted timestamps.

Syntax

db.collection.aggregate([
    { "$unwind": "$arrayField" },
    { 
        "$project": {
            "fieldName": 1,
            "DayOfMonth": {
                "$dayOfMonth": {
                    "$add": [new Date(0), { "$multiply": ["$timestampField", 1000] }]
                }
            }
        }
    }
]);

Sample Data

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 the collection ?

db.demo209.find().pretty();
{
    "_id": "101",
    "details": [
        {
            "dat": 1528929908,
            "Name": "Chris"
        },
        {
            "dat": 1529082069,
            "Name": "Carol"
        }
    ],
    "Age": 25,
    "CountryName": "US"
}

Example

Convert the timestamp field and extract 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]
                    }]
                }
            }
        }
    }
]);
{ "_id": "101", "Age": 25, "CountryName": "US", "Name": "Chris", "DayOfMonth": 13 }
{ "_id": "101", "Age": 25, "CountryName": "US", "Name": "Carol", "DayOfMonth": 15 }

How It Works

  • $unwind flattens the details array into separate documents
  • $multiply converts Unix timestamp to milliseconds (multiply by 1000)
  • $add adds milliseconds to Date(0) to create a proper Date object
  • $dayOfMonth extracts the day number (1-31) from the resulting date

Conclusion

Use $dayOfMonth with timestamp conversion to extract day values during projection. The $multiply and $add operators convert Unix timestamps to MongoDB Date objects for date extraction operations.

Updated on: 2026-03-15T01:44:35+05:30

368 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements