0

I have the following query:

@Query(value = "{ '_id': { \$in : ?0 } }", fields = "{ 'ids': '\$_id', '_id': 0 }")
fun findExistingIds(ids: Set<ObjectId>): Mono<ExistingIds>

The ExistingIds is a class that contains a List of Strings:

data class ExistingIds(val ids: List<String>)

What I want to achieve is the above query to return a list of the existing ids, but instead it returns the ids separately and not all in one. (And thats the reason I get the following exception)

Caused by: org.springframework.dao.IncorrectResultSizeDataAccessException: Query {...} returned non unique result.

I tested the query on Mongo Compass as well and this is the result enter image description here

I also tried to have it as an array but again it creates separate arrays as enter image description here

Any idea how I can solve this? Thank you very much for your time and help!

Aris
  • 984
  • 8
  • 22
  • you can do this using `$aggregate` and `$push` [mongoplayground](https://mongoplayground.net/p/LybNaQ71iyJ) – 1sina1 Mar 01 '22 at 17:43
  • @1sina1 thanks for your answer, so that means instead of `@Query` I must use `@Aggregation`? – Aris Mar 01 '22 at 18:02
  • 1
    yeah you must use [@aggregation](https://docs.mongodb.com/manual/aggregation/) but sorry idk about `spring-boot` – 1sina1 Mar 01 '22 at 18:17
  • No worries, thanks for the clarification, I will rewrite the query as an aggregation – Aris Mar 01 '22 at 20:14

1 Answers1

0

Based on @1sina1 answer I rewrote the @Query to @Aggregation as:

    //@Query(value = "{ '_id': { \$in : ?0 } }", fields = "{ 'ids': '\$_id', '_id': 0 }")
    @org.springframework.data.mongodb.repository.Aggregation(
        value = [
            "{ '\$match': { '_id': { '\$in' : ?0 } } }",
            "{ '\$project': { 'ids':'\$_id', '_id': 0 } }",
            "{ '\$group': { '_id': null, 'ids': { '\$push': '\$ids' } } }",
            "{ '\$project': { 'ids': 1, '_id': 0 } }"
        ]
    )
    fun findExistingIds(ids: Set<ObjectId>): Mono<ExistingIds>
Aris
  • 984
  • 8
  • 22