2

I have native Mongo query

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


Reposiroty

Page<NetworkObject> findByCreatedById(String userId, Pageable pageable);


I tried such like this

@Query(value = "[ {'$match': {'createdById': ?#{[0]} }}, {'$group': {'_id': '$uID', 'latest': {'$max': '$latest'}, 'createdById': {'$first': '$createdById'}}}]"
Page<NetworkObject> findByCreatedById(String userId, Pageable pageable);


but i have an error

org.bson.BsonInvalidOperationException: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is ARRAY.


seems that i must be changet to Aggregation query but i dont worked with it yet.

Update
Create Aggregation

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


But it returns me all collection elements by createdById.

0 Answers0