8

I want to format the date time into an specific format on the mongo shell output

My query

db.getCollection('people').find({
        date: { 
            $gte: ISODate("2017-04-24T14:04:34.447Z") 
        }
    },
    {
        _id: 0,
        age: 0,

    }
);

My output against this query:

/* 1 */
{
    "user_id" : "bcd020",
    "status" : "D",
    "date" : ISODate("2017-04-24T14:04:34.447Z")
}

/* 2 */
{
    "user_id" : "bcd021",
    "status" : "D",
    "date" : ISODate("2017-04-24T14:04:34.447Z")
}

What i want is to format the datetime in the output something like,

/* 1 */
    {
        "user_id" : "bcd020",
        "status" : "D",
        "date" : 2017-04-24 14:04:34
    }

    /* 2 */
    {
        "user_id" : "bcd021",
        "status" : "D",
        "date" : 2017-04-24 14:04:34
    }
Abdul Moiz
  • 1,123
  • 1
  • 13
  • 31
  • 4
    Use `{ $project: { date: { $dateToString: { format: "%Y-%m-%d %H:%M:%S", date: "$date" } } } }` in aggregation pipeline – s7vr Apr 24 '17 at 15:06
  • yes i saw this too in mongo docs, so its not possible with out aggregation? – Abdul Moiz Apr 24 '17 at 15:07
  • I doubt it. You may just get documents, iterate and use javascipt to format the date. – s7vr Apr 24 '17 at 15:16
  • ok thank veeram, put an answer if possible for you, the javascript way. – Abdul Moiz Apr 24 '17 at 15:19
  • Np. `ISODate` i s just a wrapper over javascript date. So you should be able to do everything that you do on regular date object. See if this helps you. http://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date – s7vr Apr 24 '17 at 15:29

1 Answers1

7

Solution is using aggregation pipeline as stated by Veeram in comments section

db.getCollection('people').aggregate([
    {
        $project:{
            datetime: {$dateToString: {format: "%G-%m-%d %H:%M:%S",date: "$datetime"}},
            age : 1
        }
    }
]);
Abdul Moiz
  • 1,123
  • 1
  • 13
  • 31