MongoDb Java Driver syntax for converting a Date field to a String

694 views
Skip to first unread message

him...@googlemail.com

unread,
Dec 31, 2016, 10:57:58 PM12/31/16
to mongodb-user
Hi,

I have the follwoing Mongo Shell query where I need to convert the" created" date field to to a formatted string. Can someone give me the syntax for MongoDB Java driver synatx for doing that?

db.Merchant.aggregate([
                   {$project: {
                               yearMonthDay: { $dateToString: { format: "%Y-%m-%d", date: "$createddate" } }
                               ,time:        { $dateToString: { format: "%H:%M:%S:%L", date: "$createddate" } }
                             }},
                   { $sort: {createddate : -1}}
                   ])

Kevin Adistambha

unread,
Jan 3, 2017, 11:44:09 PM1/3/17
to mongodb-user

Hi,

I have the follwoing Mongo Shell query where I need to convert the” created” date field to to a formatted string. Can someone give me the syntax for MongoDB Java driver synatx for doing that?

One way to do this is to use the Document.parse() method, passing the relevant JSON string:

Document projectStage = Document.parse(
    "{yearMonthDay: {$dateToString: { format: '%Y-%m-%d', date: '$createddate'}},"
  + " time:         {$dateToString: { format: '%H:%M:%S:%L', date: '$createddate'}}}");
Document sortStage = Document.parse("{createddate : -1}");

MongoIterable<Document> agg = collection.aggregate(
    Arrays.asList(
        sort(sortStage),
        project(projectStage)
    )
);
for(Document doc : agg) {
    System.out.println(doc.toJson());
}

The snippet above should work with Java driver 3.4.0.

Please note that in the snippet above, I put the sort() stage above the project() stage in contrast to the original query. This is because the sort() stage in the original query doesn’t do anything, since it was specified to sort by the field createddate, which doesn’t exist anymore after the project() stage.

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages