Собственный запрос MongoDB с Aggreagtion для запроса в Java - PullRequest
0 голосов
/ 15 января 2019

У меня есть собственный запрос Mongo

[
{
    $match: {
        createdById: "5c3cac81989a8469d435f3b2"
    }
}, {
    $group: {
        _id: "$uID",
        latest: {
            $max: "$latest"
        },
        createdById: {
            $first: "$createdById"
        }
    }
}
]


Reposiroty

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();


Но он возвращает мне все элементы коллекции с помощью creatById.

...