SATURN  RING  STATION

At a distant space view post, we chat about codes.

Spring Data MongoDB: custom location/date query make easy with MongoTemplate.

Spring Data is popular for its easy annotation and auto CRUD implementation with Repository interface. Spring Data MongoDB is no exception. It’s indeed handy and rapid. It also come with extra helper methods like:

which covers quite a lot of ground. However once you want to walk off the path a little bit, you need to bring back the custom query. I found the MongoDB official Java Driver not that helpful. Yes, it’s the fundamental but is also cumbersome, lack of document and requires redo-configuration(Spring Data already does it for you). Spring Data MongoDB comes with a well built tool for you: MongoTemplate

Here is a demonstration, a method return a list of events happens within distance of a point, is certain type and is within certain date range:

 

You basically construct the MongoDB query right in Java. Combining with Java 8 new date/time package life is easy! You can tell even dynamic query is easy by adding/skipping Criterias. Great job Spring Data team~

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Spring Data MongoDB: custom location/date query make easy with MongoTemplate.