简体   繁体   中英

MongoDB Spring data, max aggregate with complex condition

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.

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"}
    }},    

])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM