Skip to content

Criteria do not match when _id is of type Date. #5092

@kfickel

Description

@kfickel

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions