fear_matrix
fear_matrix

Reputation: 4960

How to get first and last date value using pymongo

I would like to get first and last date when doing a sort for the latest record in pymongo.

For example below is my query: set1 = db.set1.aggregate([{'$sort': {'date':-1}},{"$limit" : 6 }])

Which gives me the below output. I know I can do -1 and positive 1 to get the first and last date and store it in a variable but is there a better way to do it.

OUTPUT

'2014-05-15', '2014-05-16', '2014-05-17', '2014-05-18', '2014-05-19', '2014-05-20'

I just want the first and last date value and nothing in between.

Upvotes: 1

Views: 487

Answers (1)

Vadim Landa
Vadim Landa

Reputation: 2834

Just use the $first and $last aggregation operators:

    db.set1.aggregate([
        {'$sort': {'date': 1}},
        {'$group': {'_id': None, 'first': {'$first': '$date'}, 'last': {'$last': '$date'}}}
    ])

Upvotes: 2

Related Questions