2

我有本地 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 返回我所有的集合元素。

4

0 回答 0