Implement $dateToString on array items with MongoDB

To implement $dateToString on array items in MongoDB, use the $map operator inside an aggregation pipeline to transform date fields within array elements into formatted strings.

Syntax

db.collection.aggregate([
    {
        $project: {
            "arrayField": {
                $map: {
                    "input": "$arrayField",
                    "as": "item",
                    "in": {
                        "field1": "$$item.field1",
                        "dateField": {
                            $dateToString: {
                                "format": "%Y-%m-%d",
                                "date": "$$item.dateField"
                            }
                        }
                    }
                }
            }
        }
    }
]);

Sample Data

db.demo104.insertOne({
    "AppName": "Online Book",
    "Details": [
        {
            "ClientName": "Chris",
            "Deadline": new ISODate("2020-03-10")
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e2ed7fd9fd5fd66da21446f")
}

Display the document to verify the data ?

db.demo104.find().pretty();
{
    "_id": ObjectId("5e2ed7fd9fd5fd66da21446f"),
    "AppName": "Online Book",
    "Details": [
        {
            "ClientName": "Chris",
            "Deadline": ISODate("2020-03-10T00:00:00Z")
        }
    ]
}

Example: Format Date as Month Number

Convert the Deadline field in the Details array to show only the month number ?

db.demo104.aggregate([
    { "$match": {} },
    {
        "$project": {
            "AppName": 1,
            "Details": {
                "$map": {
                    "input": "$Details",
                    "as": "out",
                    "in": {
                        "ClientName": "$$out.ClientName",
                        "Deadline": {
                            "$dateToString": {
                                "format": "%m",
                                "date": "$$out.Deadline"
                            }
                        }
                    }
                }
            }
        }
    }
]);
{
    "_id": ObjectId("5e2ed7fd9fd5fd66da21446f"),
    "AppName": "Online Book",
    "Details": [
        {
            "ClientName": "Chris",
            "Deadline": "03"
        }
    ]
}

How It Works

  • $map iterates through each element in the Details array
  • $$out represents the current array element being processed
  • $dateToString converts the ISODate to a formatted string using the specified format
  • Format "%m" extracts the month as a two-digit number (01-12)

Conclusion

Use $map with $dateToString in aggregation pipelines to transform date fields within arrays. This approach preserves the array structure while formatting dates according to your requirements.

Updated on: 2026-03-15T01:55:16+05:30

312 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements