Home > Back-end >  Convert mongodb query into Spring data mongodb syntax
Convert mongodb query into Spring data mongodb syntax

Time:02-02

I am trying to convert this query spring data mongo syntax but facing issue with $add operator.

{
        "$project":
            {
              
                "nextYear": {
                    "$dateFromParts":
                        {
                            "year": { "$add": [{ "$year": "$today" }, 1] },
                            "month": { "$dayOfMonth": "$joiningDate" },
                            "day": { "$month": "$joiningDate" }

                        }

                }
            }
    }

Tried this without $add it is working, but cant find any documentation regarding $add.

 aggregationOperations.add(Aggregation.project()                       
                    .and(DateOperators.DateFromParts.dateFromParts()
                            .year(DateOperators.Year(yearOf("today")))
                            .month(dateOf("joiningDate").dayOfMonth())
                            .day(monthOf("joiningDate"))).as("nextYear"));

CodePudding user response:

If pipeline stage looks too difficult or you don't know how to convert it using spring, just try to use this way

  import org.bson.Document;
  import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
  ...

  AggregationOperation project = ctx -> Document.parse("""
         { "$project": {
          
            "nextYear": {
                "$dateFromParts":
                    {
                        "year": { "$add": [{ "$year": "$today" }, 1] },
                        "month": { "$dayOfMonth": "$joiningDate" },
                        "day": { "$month": "$joiningDate" }

                    }

            }
        }}
            """);

CodePudding user response:

Found the solution.

Used java.util.Calendar to get year value and passed the values to dateFromParts year function

 Calendar calendar = Calendar.getInstance();
 calendar.setTime(new Date());


 aggregationOperations.add(Aggregation.project()                       
                    .and(DateOperators.DateFromParts.dateFromParts()
                            .year(calendar.get(Calendar.YEAR)   1)
                            .month(dateOf("joiningDate").dayOfMonth())
                            .day(monthOf("joiningDate"))).as("nextYear"));
  •  Tags:  
  • Related