Implement $dateToString on array items with MongoDB



To implement $dateToString on array items, use aggregate() in MongoDB. Let us create a collection with documents −

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

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

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

This will produce the following output −

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

Following is the query to implement $dateToString on array items −

> db.demo104.aggregate([ ...    { "$match": {}}, ...       { "$project": { ...          "title": 1, ...          "Details": { ...             "$map": { ...                "input": "$Details", ...                "as": "out", ...                "in": { ...                   "ClientName": "$$out.ClientName", ...                   "Deadline": { ...                   "$dateToString": { "format": "%m", "date": "$$out.Deadline" } ...                } ...             } ...          } ...       } ...    }} ... ])

This will produce the following output −

{ "_id" : ObjectId("5e2ed7fd9fd5fd66da21446f"), "Details" : [ { "ClientName" : "Chris", "Deadline" : "03" } ] }
Updated on: 2020-03-30T11:33:48+05:30

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements