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:

List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);

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:


    import org.springframework.data.geo.Circle;
    import org.springframework.data.geo.Distance;
    import org.springframework.data.geo.Metrics;
    import org.springframework.data.geo.Point;
    import org.springframework.data.mongodb.core.MongoOperations;
    import org.springframework.data.mongodb.core.query.Criteria;
    import org.springframework.data.mongodb.core.query.Query;

    @Autowired
    MongoOperations mongoOpt;

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");

	public List<Event> findEventByLocationAndTime(double lng, double lat, int miles, String dateStr, int type) {
	    Distance distance = new Distance(miles, Metrics.MILES);
	    Point point = new Point(lng, lat);
	    Circle circle = new Circle(point, distance);
	    
	    Criteria geoC = Criteria.where("location").withinSphere(circle);
	    Criteria dateC = Criteria.where("date")
					.gte(LocalDate.parse(dateStr, dtf).minusDays(1).atStartOfDay())
					.lt(LocalDate.parse(dateStr, dtf).plusDays(2).atStartOfDay())	
	    Criteria typeC = Criteria.where("type").is(type);
	    
	    Query query = Query.query(geoC);
	    query.addCriteria(dateC);
	    query.addCriteria(typeC);
	    
	    return mongoOpt.find(query, Event.class);
	}

 

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~

 

2 Comments

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

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