转换mongo聚合(具有组和大小)以在Spring数据中查询

时间:2018-11-21 08:25:36

标签: spring mongodb spring-data spring-data-mongodb

在我的MongoDB中,我有这样的文档:

{
    "_id" : ObjectId("5bf3cd1c6b86db2c84d"),
    "_class" : "Log",
    "data" : {
        "devices" : [ 
             {
                "id": "12364",
        "name":"name"
             }, 
             {
                "id": "12346",
        "name":"name"
            }, 
            {
                "id": "12345",
        "name":"name"
            }
        ]
    }
}

我想返回设备数量,所以我创建了查询:

db.getCollection('coll').aggregate(
{$group: { _id: null, totalSize: { $sum: { $size: "$data.devices"}} }})

返回我的

{ "_id" : null, "totalSize" : 6 }

但是如何创建在Spring Data中返回“ totalSize”的方法?

我被卡住了,我不知道如何解决:

public Long countDevices() {
        GroupOperation groupOperation= Aggregation.group("_id").sum("_id");

        Aggregation aggregation = Aggregation.newAggregation(groupOperation);

        mongoOperations.aggregate(matchOperation,)

        return ...
    }

以下解决方案似乎可行,但其外观和性能并不那么好

public Long count(Criteria searchCriteria) {

     Aggregation aggregation = Aggregation.newAggregation(
             Aggregation.match(searchCriteria),
             Aggregation.unwind("data.device")
     );
        AggregationResults aggregationResults = mongoOperations.aggregate(aggregation,"coll", DBObject.class);
        return (long) aggregationResults.getMappedResults().size();

    }

0 个答案:

没有答案