3

蒙戈文件:春数据蒙戈模板 - 计数的数组

{ 
    "_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

它很可能,$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(); 
+0

这其中,'现在是Criteria.where(...) – dragonalvaro

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"]}}}]}

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}