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}