mongo中的$ datetostring不起作用

时间:2015-03-18 15:20:07

标签: mongodb mongodb-query mongodb-java

我有一个问题,让我忙了3天,还在和它斗争:我有mongodb查询如下:

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

现在我正在尝试将其转换为java但我真的不知道如何转换此行:

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

我尝试了这段代码,但根本没有工作:

 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);

但是我收到以下错误:

  

com.mongodb.CommandFailureException:

     

{" serverUsed" :" ...." ," errmsg" :"例外:无效
  operator' $ dateToString'" ,"代码" :15999," ok" :0.0}

有没有人有任何想法?

1 个答案:

答案 0 :(得分:1)

我在集合中插入了一个示例数据。

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

我可以使用以下java代码获取聚合查询的所需输出:

    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);
    }

有关Java驱动程序和聚合的更多详细信息,请参阅:http://docs.mongodb.org/ecosystem/tutorial/use-aggregation-framework-with-java-driver/