And*_*ins 4 java mongodb spring-data mongodb-query aggregation-framework
蒙戈文件:
{
"_id" : "1",
"array" : [
{
"item" : "item"
},
{
"item" : "item"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我的mongo shell query看起来像这样:
db.getCollection('collectionName').aggregate(
{$match: { _id: "1"}},
{$project: { count: { $size:"$array" }}}
)
Run Code Online (Sandbox Code Playgroud)
无论如何要使用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);
Run Code Online (Sandbox Code Playgroud)
我想我只是缺少project逻辑,但我不确定是否可以在$size or equivalent这里做。
这是很可能的话,$size运营商支持(见DATAMONGO-979和它的实现在这里)。您的实现可以遵循以下示例:
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();
Run Code Online (Sandbox Code Playgroud)