user3916614
user3916614

Reputation: 1

Maximum value in MongoDb

I have many records in Dbname in Collectionname

    "_id" : ObjectId("53e32f83bca58515b6eee86e"),
    "data" : [{              
        "id" : "7676722",
        "created_time" : "2014-03-16T17:06:49+0000"
    }]    
….

how select maximum of created_time in Dbname in Collectionname ?

sql analog = select max(created_time) from Dbname.Collectionname

Upvotes: 0

Views: 68

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311975

You can do this with aggregate:

db.test.aggregate([
    // Unwind the data array to one element per doc
    {$unwind: '$data'},
    // Order those by created_time descending
    {$sort: {'data.created_time': -1}},
    // Take the first one
    {$limit: 1},
    // Project just the needed value
    {$project: {_id: 0, max_created_time: '$data.created_time'}}
])

Upvotes: 1

Related Questions