0

I am using mongodb as a document oriented database, and spring data as the ODM with it. I am facing hard time, performing a max aggregation on complex bson structure. I have to find the max date, from all documents but if the document has an embedded document, it has to consider that embedded document for the max date. Here is an example, lets suppose i have a collection name person and person collection contains following documents.

{
     "_id" : ObjectId("55def1ceb5b5ed74ddf2b5ce"),
     "name" : "abc",
     "birth_date_time" :  '15 June 1988'
      "children" : {
        "_id" : ObjectId("55def1ceb2223ed74ddf2b5ce"),
        "name" : "def",
        "birth_date_time" :  '10 April 2010'
      }
},
{
    "_id" : ObjectId("55def1ceb5b5ed74dd232323"),
    "name" : "xyz",
    "birth_date_time" :  '15 June 1986'
},
{
     "_id" : ObjectId("55def1ceb5b5ed74ddf2b5ce"),
     "name" : "mno",
     "birth_date_time" :  '18 March 1982'
      "children" : {
        "_id" : ObjectId("534ef1ceb2223ed74ddf2b5ce"),
        "name" : "pqr",
        "birth_date_time" :  '10 April 2009'
      }
}

It should return 10 April 2010 as this the max birth date for a person in the collection person. I want to know who to achieve it using spring data repository.

1 Answer 1

1

Here are the MongoDB aggregations. They should be easily implemented in Spring Data.

db.person.aggregate([
    {$group: {
        _id: null,
        maxDate: {$max : { 
            $cond: [ 
                {$gt : ["$birth_date_time","$children.birth_date_time"]}, 
                "$birth_date_time", 
                "$children.birth_date_time"
            ]}}
    }}  
])

or using a $project:

db.person.aggregate([{
    $project: {
        mDate: {
            $cond: [
                {$gt : ["$birth_date_time","$children.birth_date_time"]}, 
                "$birth_date_time", 
                "$children.birth_date_time"
            ]
        }
    }},
    {$group: {
        _id: null,
        maxDate: {$max : "$mDate"}
    }},    

])
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks fo the answer... I don't want to use mongoTemplete it will be extra injection on the bean for this specific case ? @MirceaG is there any way to map this aggregated query with spring data repository interface using Query annotation ?
Sorry, I'm not familiar with the capabilities of @Query. I'm usually using the Spring Data aggregation builder or the Mongo Java Driver DBCollection.aggregate when operations (like $redact) are not supported by Spring

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.