9

My pojo

public class PacketData implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    private final String token = UUID.randomUUID().toString();

    private final ZonedDateTime arrived = ZonedDateTime.now();
}

I plan to use like following.

@Query("?")
List<PacketData> findPacketArrivedBetween(ZonedDateTime startDate, ZonedDateTime endDate);

Is there a way i can put the following query to the above query annotation and how i can do greater than and less than logic

Query query = new Query().addCriteria(Criteria.where("arrived").gte(startDate).lte(endDate));
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212
  • Spring Data MongoDB has no built-in support for `ZonedDateTime`, only `LocalDateTime`. Using `ZonedDateTime` requires a [custom converter](http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping-explicit-converters) to persist the timezone. – mp911de Feb 12 '17 at 17:34

1 Answers1

11

You can try following couple of ways.

Without Query Annotation.

List<PacketData> findByArrivedBetween(ZonedDateTime startDate, ZonedDateTime endDate);

With Query Annotation.

@Query("{'arrived': {$gte: ?0, $lte:?1 }}")
List<PacketData> findPacketArrivedBetween(ZonedDateTime startDate, ZonedDateTime endDate);
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • This is not a valid answer as MongoRepository does not support ZonedDateTime: the MongoDB driver uses the java.util.Date type – user666 Dec 10 '18 at 11:14
  • 1
    @user666 the user was already using custom converter to accommodate ZonedDateTime. More here https://stackoverflow.com/questions/41127665/zoneddatetime-with-mongodb/41146758#41146758 – s7vr Dec 10 '18 at 13:20
  • is there a way to send epoch timestamp in @query? for example in MongoDB compass we case use new Date([epoch integer]) and it works well. Is this posisble using spring boot jpa? – user666 Dec 10 '18 at 13:44
  • I tried this on Mongo 4.0.9 and the between using `@Query` annotation doesn't seem to work. But the query method technique works as expected. Any idea why? – Romeo Sierra Jun 04 '19 at 10:33
  • I think it's the findByArrivedBetween is actually returning lt and gt strictly not or equal to. – fayssal el ansari Jun 29 '23 at 08:01