Closed
Description
Having problem using query method, as query generated by spring-data-mongodb is consist of string type _id, not ObjectId.
@Document("test_entity")
public class TestEntity {
@MongoId(targetType = FieldType.OBJECT_ID)
private String id;
private String testField;
}
public interface TestRepository extends MongoRepository<TestEntity, String> {
List<TestEntity> findAllByIdGreaterThan(String id);
}
Entity and Repository are declared like above code.
And I tested by below simple test code.
@SpringBootTest
class TestRepositoryTest {
@Autowired
private TestRepository testRepository;
@Test
void test() {
TestEntity entity = new TestEntity();
testRepository.save(entity);
List<TestEntity> result = testRepository.findAllByIdGreaterThan("000000000000000000000000");
}
}
It is supposed to return all documents in DB, as "000000000000000000000000" is minimum value of ObjectId. But nothing returned.
Also, It seems Mongotemplate is querying by string type _id.
2023-08-31T22:20:55.784+09:00 DEBUG 72457 --- [ Test worker] o.s.d.m.r.query.MongoQueryCreator : Created query Query: { "id" : { "$gt" : "000000000000000000000000"}}, Fields: {}, Sort: {}
2023-08-31T22:20:55.789+09:00 DEBUG 72457 --- [ Test worker] o.s.data.mongodb.core.MongoTemplate : find using query: { "_id" : { "$gt" : "000000000000000000000000"}} fields: Document{{}} for class: class com.example.mongodb_test.entity.TestEntity in collection: test_entity
I could solve this problem with a temporary solution, by using custom @query like below, with appropriate debug log using $oid.
@Query("{'_id': {'$gte': {'$oid': ?0}}}")
List<TestEntity> findAllByIdGreaterThan(String id);
2023-08-31T22:24:31.959+09:00 DEBUG 72886 --- [ Test worker] o.s.d.m.r.query.StringBasedMongoQuery : Created query Document{{_id=Document{{$gte=000000000000000000000000}}}} for Document{{}} fields.
2023-08-31T22:24:31.965+09:00 DEBUG 72886 --- [ Test worker] o.s.data.mongodb.core.MongoTemplate : find using query: { "_id" : { "$gte" : { "$oid" : "000000000000000000000000"}}} fields: Document{{}} for class: class com.example.mongodb_test.entity.TestEntity in collection: test_entity
But still I can't use query method with _id.
Am I using query method in wrong way? or It's id type bug?