HMdeveloper
HMdeveloper

Reputation: 2884

$datetostring in mongo does not work

I have a question that has made me busy for 3 days and still fighting with it: I have mongodb query as follow:

 db.test.aggregate([ 
  { 
     $project: { 
         yearMonthDay: { 
              $dateToString: { format: "%Y-%m-%d", date: "$date" } 
         } 
     } 
  } 
]) 

now I am trying to convert it to java but I really do not know how to convert this line:

yearMonthDay: { 
       $dateToString: { format: "%Y-%m-%d", date: "$date" } 
} 

I tried this code but not working at all:

 DBObject project = new BasicDBObject("_id", 0);
 DBObject format = new BasicDBObject("format","%Y-%m-%d");
 format.put("date", "$date");
 DBObject formattedDate = new BasicDBObject("$dateToString",format);
 project.put("yearMonthDay",formattedDate);

but I get the following error:

com.mongodb.CommandFailureException:

{ "serverUsed" : "...." , "errmsg" : "exception: invalid
operator '$dateToString'" , "code" : 15999 , "ok" : 0.0}

Does anyone have any idea?

Upvotes: 2

Views: 4577

Answers (1)

Dev
Dev

Reputation: 13753

I inserted a sample data in collection.

 {
   "_id" : 1,
   "item" : "abc",
   "price" : 10,
   "quantity" : 2,
   "date" : ISODate("2014-01-01T08:15:39.736Z")
 }

I am able to get the desired output for your aggregation query using this java code:

    DBCollection collection = db.getCollection("collection");
    DBObject project = new BasicDBObject();
    DBObject format = new BasicDBObject("format", "%Y-%m-%d");
    format.put("date", "$date");
    DBObject formattedDate = new BasicDBObject("$dateToString", format);
    project.put("yearMonthDay", formattedDate);
    DBObject aggregate = new BasicDBObject("$project", project);

    List<DBObject> pipeline = Arrays.asList(aggregate);
    AggregationOutput output = collection.aggregate(pipeline);
    for (DBObject result : output.results()) {
        System.out.println(result);
    }

For more details on Java Driver and Aggregation, please find : http://docs.mongodb.org/ecosystem/tutorial/use-aggregation-framework-with-java-driver/

Upvotes: 1

Related Questions