如何在Java中的Spring Data Aggregation中实现$ size

时间:2019-01-08 12:39:51

标签: java mongodb

如何使用Spring Data mongodb在Java中实现以下代码

db.profil.aggregate([
   { "$match": { "typ": "Organisation" } },
   { "$group": {
       "_id": null,
        "count": {
            "$sum": { "$size": "$foos" }
        }
    } }
])

1 个答案:

答案 0 :(得分:0)

MongoDB具有用于Java的Aggregation框架,以支持所有聚合API。

尝试以下操作:

import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Projections.*;

Bson match = match(eq("typ", "Organisation")));
Bson projection = new Document("$size", "$foos" );
Bson group = group("$_id", Accumulators.sum("count",projection));
MongoCursor<Document> cursor = collection.aggregate(asList(match, group)).iterator();