Spring数据中的属性MongoDB聚合始终为null

时间:2017-06-21 13:51:21

标签: spring mongodb spring-data

我有以下代码尝试按modelId分组并显示两个不同的计数:

 DBObject query = new BasicDBObject("$group", new BasicDBObject(
            "_id", "$response.modelId")
            .append("okCount", new BasicDBObject(
                            "$sum", new BasicDBObject(
                            "$cond", new Object[]{new BasicDBObject("$and", new Object[]{new BasicDBObject("$ne", new Object[]{"$responseData", null}), new BasicDBObject("$eq", new Object[]{"$responseStatus", null})}), 1, 0})
                    )
            ).append("notOkCount", new BasicDBObject(
                            "$sum", new BasicDBObject(
                            "$cond", new Object[]{new BasicDBObject("$ne", new Object[]{"$responseStatus", null}), 1, 0})
                    )
            ));
    Aggregation aggregation = newAggregation(match(Criteria.where("response.modelId").ne(null)), new CustomGroupOperation(query));
    AggregationResults<RequestTraceCount> results = mongoTemplate.aggregate(aggregation, "RequestHistory", RequestTraceCount.class);

我确实得到了正确的计数但是因为modelId嵌套在响应中,所以在每个结果中我得到_id等于null。

我该如何解决这个问题?

这就是结果:

 [{"okCount": 301,"notOkCount": 66,"_id": null},{"okCount": 11,"notOkCount": 6,"_id": null}]

这是集合中的示例文档:

{
"_id" : "01e71704-0f40-4c34-8685-dee990b6f38c",
"response" : {
    "id" : "6b728429-2f28-4588-b045-15198a8c50ac",
    "modelId" : "c902cdbc-b4e2-4ca2-a2eb-beb827705325",
    "modelCode" : "EDBW",
    "validFrom" : 201507,
    "validTo" : 201909
},
"responseData" : { /* large object */
    },
"responseStatus" : null
}

以下是RequestTraceCount和CustomGroup Operation

public class RequestTraceCount {
@JsonProperty("_id")
private UUID modelId;
private int okCount;
private int notOkCount;

public UUID getModelId() {
    return modelId;
}

public void setModelId(UUID modelId) {
    this.modelId = modelId;
}

public int getOkCount() {
    return okCount;
}

public void setOkCount(int okCount) {
    this.okCount = okCount;
}

public int getNotOkCount() {
    return notOkCount;
}

public void setNotOkCount(int notOkCount) {
    this.notOkCount = notOkCount;
}
}






class CustomGroupOperation implements AggregationOperation {
private DBObject operation;

public CustomGroupOperation(DBObject operation) {
    this.operation = operation;
}

@Override
public DBObject toDBObject(AggregationOperationContext context) {
    return context.getMappedObject(operation);
}
}

1 个答案:

答案 0 :(得分:0)

您可以使用spring mongo注释@Field("_id")将其正确映射回来。

import org.springframework.data.mongodb.core.mapping.Field;

@Field("_id")
private UUID modelId;