Criteria do not match when _id is of type Date.
When _id is a Date field, MongoTemplate is not able to fetch any entries using Criteria-queries.
Using com.mongodb.client.MongoCollection works out as expected, also selecting for non-_id Date-fields works out fine. It's just the combination of MongoTemplate and Date _ids seems to be the problem.
See the following code snippet reproducing the problem:
// [...]
docs.add(new Document("_id", new Date(123456)).append("value", new Date(654321)));
mongoTemplate.insert(docs, COLLECTIONNAME);
// [...]
@Test
void testFindByDateId() {
Document doc = collection.find(new Document().append("_id", new Date(123456))).first();
assertNotNull(doc); // passes
}
// [...]
@Test
void testFindByDateIdWithMongoTemplate() {
var criteria = Criteria.where("_id").is(new Date(123456));
var query = new Query(criteria);
List<Document> doc = mongoTemplate.find(query, Document.class, COLLECTIONNAME);
assertEquals(1, doc.size()); // fails, would expect pass
assertNotNull(doc.get(0));
}
@Test
void testFindByDateValueWithMongoTemplate() {
var criteria = Criteria.where("value").is(new Date(654321));
var query = new Query(criteria);
List<Document> doc = mongoTemplate.find(query, Document.class, COLLECTIONNAME);
assertEquals(1, doc.size());
assertNotNull(doc.get(0)); // passes
}
// [...]
For a full working example, see https://github.com/fkreisEnbw/spring-date-time-as-id.
Thank you for getting in touch.
This is due to the conversion of _id values that are valid ObjectIds into the such by the mapping layer. The documentation has a blank spot for the Date conversion.
I agree that the automatic conversion into ObjectId is an area that we should improve on. At least provide users a with a way of opting out. Especially when working with raw types like Document since using @MongoId is not an option in those scenarios.
For the time being you can fall back to driver API as outlined below
mongoTemplate.execute(COLLECTIONNAME, collection -> {
return collection.find(new Document("_id", ...
});
Hey Chistoph, thanks for the quick and helpful response! We'd be glad to see this improve in the future!