2016-02-10 141 views
2

我正在使用mongodb.I必须在我的弹簧数据mongo db中为$ date使用聚合查询。这是我的用户集合。

{ 
    "_id" : NumberLong(70289), 
    "_class" : "com.samepinch.domain.user.User", 
    "age" : 25, 
    "roles" : [ 
     "ROLE_MODERATOR", 
     "ROLE_USER" 
    ], 
    "firstName" : "Abhi", 
    "lastName" : "Saini", 
    "email" : "[email protected]", 
    "createdDate" : ISODate("2015-12-04T12:29:57.604Z"), 
    "updatedDate" : ISODate("2016-02-10T06:23:13.314Z") 
} 

这是我的MongoDB查询

db.users.aggregate([{ $project : { month_joined : { $month : "$createdDate" } } } ,{ $group : { _id : {month_joined:"$month_joined"} , number : { $sum : 1 } } },{ $sort : { "_id.month_joined" : 1 } }]) 

查询给了我希望的结果为:

{ "_id" : { "month_joined" : 1 }, "number" : 19 } 
{ "_id" : { "month_joined" : 2 }, "number" : 7 } 
{ "_id" : { "month_joined" : 9 }, "number" : 16 } 
{ "_id" : { "month_joined" : 10 }, "number" : 12 } 
{ "_id" : { "month_joined" : 11 }, "number" : 11 } 
{ "_id" : { "month_joined" : 12 }, "number" : 13 } 

现在我必须写使用mongotemplate春天的mongodb数据这个查询。我是使用聚合的新手,他们是使用它的简单方法。请帮忙

谢谢。

回答

1

您可以尝试通过在投影操作使用SpEL andExpression然后组由组操作中的新字段第一突出的字段:

Aggregation agg = newAggregation(
    project("id").andExpression("month(createdDate)").as("month_joined"), 
    group("month_joined").count().as("number"), 
    project("number").and("month_joined").previousOperation(), 
    sort(ASC, "number") 
); 

AggregationResults<JoinCount> results = mongoTemplate.aggregate(agg, 
                "collectionName", JoinCount.class); 
List<JoinCount> joinCount = results.getMappedResults(); 

在上述经由新的聚合newAggregation创建了一个静态工厂方法,您可以向其传递聚合操作列表。这些聚合操作定义了聚合的聚合管道。

在第一步中,您通过使用SpEL andExpression与项目操作来投影输入集合中的字段。

在第二步中,您使用组操作为每个"month_joined"定义一个组,并通过count()汇总运算符汇总出现次数,并将结果收集到名为"number"的新字段中。

作为第三步骤选择字段"number"并创建具有名称"month_joined"从前一组操作而生成的_id -field(因此调用previousOperation())的别名。

作为第四步排序产生的分组month_joined文件通过其发生的列表,经由排序操作升序计数。

最后调用aggregate() MongoTemplate上的方法,以便让MongoDB以创建的Aggregation作为参数执行实际的聚合操作。


要过滤的文件获得在管道本年度,你需要项目保存日期的年份部分一个新的领域和项目后一步然后发出匹配运营商,像

Aggregation agg = newAggregation(
    project("id") 
     .andExpression("month(createdDate)").as("month_joined") 
     .andExpression("year(createdDate)").as("year"), 
    match(Criteria.where("year").is(2016)), 
    group("month_joined").count().as("number"), 
    project("number").and("month_joined").previousOperation(), 
    sort(ASC, "number") 
); 

AggregationResults<JoinCount> results = mongoTemplate.aggregate(agg, 
                "collectionName", JoinCount.class); 
List<JoinCount> joinCount = results.getMappedResults(); 
+0

当我使用项目()。 andExpression()。它要求我和表达式(字符串表达式,对象参数)。根据你的回答,我不知道如何使用它? –

+0

如前所示,您是否尝试使用'.andExpression(“month(createdDate)”)'而不是'.andExpression(“month(date)”)? – chridam

+0

其实.andExpression()是要求两个参数我。e和表达式(字符串表达式,对象参数)。我很困惑传递什么。 –

相关问题