0

I am working on a project where I use spring data mongodb. I am making a mongo query like this:

Query query = new Query();

Criteria one = Criteria.where(DB_FIELD_1).gt(1);
Criteria two = Criteria.where(DB_FIELD_2).lt(10);

Criteria final = new Criteria().andOperator(one,two);
query.addCriteria(final);

// after making the query, I am executing it using mongoTemplate

Now, I have a Date field with format YYYYMMDD. I would like to check if its month = current month. For example, if the field is 20170501, then the date's month (05) is current month (5, May). How do I extract the month value from date and check this logic along with other criteria above ( one and two )? I know there is $month to extract the month value from date. But, I do not know how to incorporate aggregate function within "Criteria" class. My final result should be something like this:

 Criteria final = new Criteria().andOperator(one,two,criteria to check month = current month);
 query.addCriteria(final);
4
  • date field is stored as String in DB? Commented May 10, 2017 at 18:01
  • its stored as Date Commented May 10, 2017 at 18:04
  • Can you add a sample document from your collection to the post ? and what is your spring mongo db version ? You will need to use projection expression for this one. Commented May 10, 2017 at 18:15
  • spring mogo db version is 1.4.1.RELEASE Commented May 10, 2017 at 19:10

1 Answer 1

1

You can use below aggregation pipeline with the current spring db version 1.10.2/ Spring 1.5.2 Boot. Include the other fields in the $project that you wish to output.

Use $addFields instead of $project for 3.4 x mongo server version.

 AggregationOperation project = Aggregation.project().and(DateOperators.dateOf(DB_FIELD_1).month()).as("field1").and(DateOperators.dateOf(DB_FIELD_2).month()).as("field2");
 AggregationOperation match = Aggregation.match(Criteria.where("field1").gt(1)
                .and("field2").lt(10));
 Aggregation aggregation = Aggregation.newAggregation(project, match);
 List<BasicDBObject> results = mongoTemplate.aggregate(aggregation, collectionname, BasicDBObject.class).getMappedResults();

Use for 1.4.1 version

AggregationOperation project = Aggregation.project().and(DB_FIELD_1).extractMonth().as("field1").and(DB_FIELD_2).extractMonth().as("field2");
Sign up to request clarification or add additional context in comments.

4 Comments

what is project() in the first line?
Sorry, it is to create $project stage. Use Aggregation.project(). Updated answer.
and also, DateOperators. I cant find that class
Okay Can you update to 1.5.2 boot version ? Btw added 1.4.1 update

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.