ilPittiz
ilPittiz

Reputation: 754

MongoDB - get $max among fields at different levels

I have a MongoDB collection with documents of this (simplified) form

{
    "_id": "Doc"
    "created": NumberLong("1422526079335")
}

Additionally, this documents may have an additional edited field

{
    "_id": "Doc"
    "created": NumberLong("1422526079335")
    "edited": {
        "date": NumberLong("1458128507498")
    }
}

What I need is to get the most recent timestamp (among created and edited.date) for a subset of these documents, matching certain conditions.

What I achieved so far is to get the most recent created timestamp

db.myCollection.aggregate([ { $match: { ... } },
                            { $project: { _id:0, created: 1 } },
                            { $group: { _id: 'latest', latest: { $max: '$created' } } }
                          ])

which returns

{ "_id" : "latest", "latest" : NumberLong("1422526079335") }

How can I integrate the check against edited.date in the $max logic above? Or alternatively is there another solution? Thanks is advance!

Upvotes: 2

Views: 747

Answers (2)

Saleem
Saleem

Reputation: 8978

Try this script. it's simple $max operator.

I have following documents in collection

{ 
    "_id" : "Doc", 
    "created" : NumberLong(1422526079335), 
    "edited" : {
        "date" : NumberLong(1458128507498)
    }
}
{ 
    "_id" : "Doc1", 
    "created" : NumberLong(1422526079335)
}

Try running following query:

db.doc.aggregate([
  { 
     $match: { ... } 
  },
  {
     $project:{
       latest:{ $max:["$created", "$edited.date"]}
     }
  }
])

Output will be:

{ 
    "_id" : "Doc", 
    "latest" : NumberLong(1458128507498)
}
{ 
    "_id" : "Doc1", 
    "latest" : NumberLong(1422526079335)
}

Upvotes: 3

profesor79
profesor79

Reputation: 9473

you can use $cond in last $project pipe - lastModifedDate makes the trick :-)

db.ill.aggregate([{
    $project:{
        lastModifedDate:{
              $cond: { 
                 if: { $gte: [ "$created", "$edited.date"] }, 
                 then: "$created", else: "$edited.date" }
        }}}])   

Upvotes: 1

Related Questions