在Java中使用聚集查询的MongoDB本机查询
我有本地Mongo查询在Java中使用聚集查询的MongoDB本机查询,java,mongodb,mongodb-query,spring-mongodb,spring-mongo,Java,Mongodb,Mongodb Query,Spring Mongodb,Spring Mongo,我有本地Mongo查询 [ { $match: { createdById: "5c3cac81989a8469d435f3b2" } }, { $group: { _id: "$uID", latest: { $max: "$latest" }, createdById: { $first: "$createdById" }
[
{
$match: {
createdById: "5c3cac81989a8469d435f3b2"
}
}, {
$group: {
_id: "$uID",
latest: {
$max: "$latest"
},
createdById: {
$first: "$createdById"
}
}
}
]
报告
似乎我必须转换为聚合查询,但我还没有使用它 更新
创建聚合
Aggregation aggregation = newAggregation(match(Criteria.where("createdById").is(userId)),
group(fields("uID").and("latest","$latest")
.and("createdById","$createdById"))
.max("$latest").as("latest")
.first("$createdById").as("createdById"));
AggregationResults<NetworkObject> results = mongoTemplate.aggregate(aggregation,"NetworkObject",NetworkObject.class);
List<NetworkObject> objects = Optional.of(results.getMappedResults()).get();
Aggregation-Aggregation=newAggregation(匹配(Criteria.where(“createdById”).is(userId)),
组(字段(“uID”)和(“最新”、“最新”)
。和(“createdById”,即“$createdById”))
.max(“$latest”).as(“latest”)
。第一个($createdById”)。作为(“createdById”);
AggregationResults=mongoTemplate.aggregate(聚合,“NetworkObject”,NetworkObject.class);
List objects=Optional.of(results.getMappedResults()).get();
但它按createdById返回所有集合元素。请参见
@Query(value = "[ {'$match': {'createdById': ?#{[0]} }}, {'$group': {'_id': '$uID', 'latest': {'$max': '$latest'}, 'createdById': {'$first': '$createdById'}}}]"
Page<NetworkObject> findByCreatedById(String userId, Pageable pageable);
org.bson.BsonInvalidOperationException: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is ARRAY.
Aggregation aggregation = newAggregation(match(Criteria.where("createdById").is(userId)),
group(fields("uID").and("latest","$latest")
.and("createdById","$createdById"))
.max("$latest").as("latest")
.first("$createdById").as("createdById"));
AggregationResults<NetworkObject> results = mongoTemplate.aggregate(aggregation,"NetworkObject",NetworkObject.class);
List<NetworkObject> objects = Optional.of(results.getMappedResults()).get();