Skip to content

Projection on the _id field returns wrong result when using @MongoId (MongoDB 4.4) #3668

Closed
@steschae

Description

@steschae

Describe the bug
Executing a MongoDB query against MongoDB 4.4 which contains a projection on the _id field with an entity class using the @MongoId annotation on a string-id field results in returned objects which have incorrect id values. In fact, the id values of all returned objects all have the same value "1".
However, when using the @Id instead of the @MongoId annotation, the same query returns the expected results containing the correct id values.

Expected behavior
The returned objects each have their correct id value.

Actual behavior
When using MongoDB 4.4: The returned objects each have the id value "1"
When using MongoDB 4.2: The returned objects each have their correct id value.

To Reproduce
I have set up an example project with test cases (https://github.com/steschae/spring-data-mongodb-id-projection-bug). The test "MongoDbVersion4_4_Test > should_find_all_person_ids_when_using_mongo_id_annotation" is the one which is failing because of this bug (https://github.com/steschae/spring-data-mongodb-id-projection-bug/runs/2818935410#step:4:33).

To reproduce, 1. create an entity class using the @MongoId annotation

@Data
public class Person {
    @MongoId
    private String id;
}
  1. Create a query with a projection on the _id field:
public interface PersonRepository extends CrudRepository<PersonWithMongoId, String> {
    @Query(value="{}", fields = "{ _id : 1 }")
    List<Person> findAllIds();
}

or

final var query = new Query();
query.fields().include(ID);
mongoTemplate.find(query, Person.class);
  1. When executing the query, all returned objects have the value "1" in the id field.

image

Configuration/Environment/Context
MongoDB 4.4
org.springframework.data:spring-data-mongodb:3.2.1
org.mongodb:mongodb-driver-sync:4.2.3

Additional information
With MongoDB 4.4 the behaviour of projection documents in MongoDB queries has changed:
(https://docs.mongodb.com/manual/release-notes/4.4-compatibility/#projection-compatibility-changes)

The query is translated to db.getCollection("persons").find({}, {"_id": "1"}) (the value of the _id projection is a string). This worked with MongoDB 4.2, but with MongoDB 4.4 the string value "1" in the projection causes the id value of the returned documents to be overidden with this value "1".
This happens somewhere in org.springframework.data.mongodb.core.convert.QueryMapper#getMappedValue, org.springframework.data.mongodb.core.convert.QueryMapper#convertId.

Metadata

Metadata

Labels

type: regressionA regression from a previous release

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions