2017-03-23 30 views
-1
([{ 
    $match: { 
     "Publication_Date": { 
      $gte: ISODate("2003-01-01T00:00:00.0Z") 
     }, 
    } 
    }, { 
    $group: { 
     _id: { 
      $year: "$Publication_Date" 
     }, 
     total: { 
      $sum: 1 
     }, 
    } 
}]) 
+1

请考虑包括从您的收藏样本文件,你已经尝试到目前为止的代码 – Veeram

回答

0

只是“翻译”到这个org.bson.Document结构(类似地图),并调用适当的措施(这是不是一个查询,在这种情况下,它是一个集合):

Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2003-01-01"); 
Document group = new Document(); 
group.put("_id", new Document("$year", "$Publication_Date")); 
group.put("total", new Document("$sum", 1)); 
AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(
    new Document("$match", new Document("Publication_Date", 
     new Document("$gte", date))), 
    new Document("$group", group) 
)); 

或使用com.mongodb.client.model包静态方法(更简洁):

AggregateIterable<Document> aggregate = collection.aggregate(Arrays.asList(
    Aggregates.match(Filters.gte("Publication_Date", date)), 
    Aggregates.group(
     new Document("$year", "$Publication_Date"), 
     Accumulators.sum("total", 1)))); 
+0

,如果我有一个另一个领域,其名称是publicationId和我有一组publicationid和由他们组我怎么做?因为这个查询适用于所有的文档,我想申请一些fixid文档,其中publicationid在集合中 –