我有本地Mongo查询
[
{
$match: {
createdById: "5c3cac81989a8469d435f3b2"
}
}, {
$group: {
_id: "$uID",
latest: {
$max: "$latest"
},
createdById: {
$first: "$createdById"
}
}
}
]
存储库
Page<NetworkObject> findByCreatedById(String userId, Pageable pageable);
我这样尝试过
@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();
但这会通过createdById返回所有集合元素。