Spring Data Mongo模板 - 计算数组

时间:2016-06-14 13:04:07

标签: java mongodb mongodb-query spring-data aggregation-framework

Mongo文件:

{
    "_id" : "1",
    "array" : [
        {
            "item" : "item"
        }, 
        {
            "item" : "item"
        }
    ]
}

我的mongo shell query看起来像这样:

db.getCollection('collectionName').aggregate(
    {$match: { _id: "1"}},
    {$project: { count: { $size:"$array" }}}
)

无论如何使用Mongo Template from Spring来实现这一点?

到目前为止,我有这个:

MatchOperation match = new MatchOperation(Criteria.where("_id").is("1"));
ProjectionOperation project = new ProjectionOperation();
Aggregation aggregate = Aggregation.newAggregation(match, project);
mongoTemplate.aggregate(aggregate, collectionName, Integer.class);

我认为我只缺少project逻辑,但我不确定是否可以在此处$size or equivalent

3 个答案:

答案 0 :(得分:4)

很有可能,支持$size运算符(请参阅DATAMONGO-979及其实现 here )。您的实现可以遵循以下示例:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

Aggregation agg = newAggregation(
    match(where("_id").is("1")), //  
    project() //
        .and("array") //
        .size() //
        .as("count")
);

AggregationResults<IntegerCount> results = mongoTemplate.aggregate(
    agg, collectionName, Integer.class
);
List<IntegerCount> intCount = results.getMappedResults();

答案 1 :(得分:0)

您可以将查询编写为

 Aggregation aggregate = Aggregation.newAggregation(Aggregation.match(Criteria.where("_id").is(1)),
            Aggregation.project().and("array").size().as("count")); mongoTemplate.aggregate(aggregate, collectionName, Integer.class);

它将执行以下查询{ "aggregate" : "collectionName" , "pipeline" : [ { "$match" : { "_id" : 1}} , { "$project" : { "count" : { "$size" : [ "$array"]}}}]}

答案 2 :(得分:0)

请在下面找到示例代码。您可以使用集合名称,集合名称类和数组字段名称相应地更改它。

    MatchOperation match = new MatchOperation(Criteria.where("_id").is("1"));
    Aggregation aggregate = Aggregation.newAggregation(match, Aggregation.project().and("array").project("size").as("count"));

    AggregationResults<CollectionNameClass> aggregateResult = mongoOperations.aggregate(aggregate, "collectionName", <CollectionNameClass>.class);

    if (aggregateResult!=null) {
        //You can find the "count" as an attrribute inside "result" key
        System.out.println("Output ====>" + aggregateResult.getRawResults().get("result"));
        System.out.println("Output ====>" + aggregateResult.getRawResults().toMap());
    }

示例输出: -

Output ====>[ { "_id" : "3ea8e671-1e64-4cde-bd78-5980049a772b" , "count" : 47}]
Output ====>{serverUsed=127.0.0.1:27017, waitedMS=0, result=[ { "_id" : "3ea8e671-1e64-4cde-bd78-5980049a772b" , "count" : 47}], ok=1.0}