Skip to content

Criteria for Mongo returns wrong results when sorting by id property #1442

Description

@harmenweber

When using criteria for mongo, sorting by the id property returns incorrect results. More precisely, the results are not sorted by the id property even though you specified a sorting by id.

Here is a concrete example.

Given the interface StringHolder:

  @Value.Immutable
  @Criteria
  @Criteria.Repository
  @JsonDeserialize(as = ImmutableStringHolder.class)
  @JsonSerialize(as = ImmutableStringHolder.class)
  @JsonIgnoreProperties(ignoreUnknown = true)
  interface StringHolder {
    @Criteria.Id
    String id();
    String value();
    @Nullable String nullable();
    Optional<String> optional();
    String[] array();
    List<String> list();
  }

When you insert a bunch of StringHolder instances into a collection and then fetch all ordered by id, you fill receive all StringHolder instances in an incorrect order. Let's be fair, there is a small chance that you get them in the correct order, but that would be by accident.

The following test fails:

  @Test
  void sortById() {
    final StringHolderRepository repository = new StringHolderRepository(this.resource.backend());

    final List<TypeHolder.StringHolder> stringHolders =
        Stream.generate(TypeHolder.StringHolder.generator()).limit(100).collect(Collectors.toList());
    Collections.shuffle(stringHolders);
    repository.insertAll(stringHolders);

    final List<String> expectedIdsInOrder =
        stringHolders.stream().map(TypeHolder.StringHolder::id).sorted().collect(Collectors.toList());

    final List<String> actualIds = repository.findAll().orderBy(StringHolderCriteria.stringHolder.id.asc()).fetch()
        .stream().map(TypeHolder.StringHolder::id).collect(Collectors.toList());

    Checkers.check(actualIds).is(expectedIdsInOrder);
  }

The reason is, that the MongoSession does not apply the PathNaming when handling the collations in the query. As a result, the id property does not get translated to Mongo's _id field. Using the PathNaming when handling the collations will solve the problem. The PathNaming is aware of the id property and will translate it to _id.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions