Programmer
Programmer

Reputation: 8727

Sort the result from a PyMongo query

I have a MongoDB query as follows :

data =  db.collection.aggregate([{"$match":{"created_at":{"$gte":start,"$lt":end}}},{"$group":{"_id":"$stage","count":{"$sum":1}}},{"$match":{"count":{"$gt":m{u'count': 296, u'_id': u'10.57.72.93'}

Which results in the following output:

{u'count': 230, u'_id': u'111.11.111.111'}
{u'count': 2240, u'_id': u'111.11.11.11'}

I am trying to sort the output by the 'count' column:

data.sort('count',  pymongo.DESCENDING)

...but I am getting the following error:

'CommandCursor' object has no attribute 'sort'

Can anyone explain the reason for this error?

Upvotes: 3

Views: 2987

Answers (3)

Blakes Seven
Blakes Seven

Reputation: 50426

Aggregation pipelines have a $sort pipeline stage:

data =  db.collection.aggregate([
   { "$match":{"created_at":{"$gte":start,"$lt":end} }},
   { "$group":{ "_id":"$stage","count":{"$sum":1} }},
   { "$match":{
       "count":{  "$gt": 296 }  # query trimmed because your question listing is incomplete
   }},
   { "$sort": { "count": -1 } }   # Actual sort stage
])

The other .sort() method is for a "cursor" which is different from what the aggregation pipeline does.

Upvotes: 0

falsetru
falsetru

Reputation: 369444

Using $sort as shown in Aggregation example:

from bson.son import SON

data =  db.collection.aggregate([
    {"$match":{"created_at":{"$gte":start,"$lt":end}}},
    {"$group":{"_id":"$stage","count":{"$sum":1}}},
    {"$match":{"count": ... }},
    {"$sort": SON([("count", -1)])}  # <---
]) 

alternative general solution: use sorted with custom key function:

data =  db.collection.aggregate(...)
data = sorted(data, key=lambda x: x['count'], reverse=True)

Upvotes: 6

Sergey Arkhipov
Sergey Arkhipov

Reputation: 156

You may want to use $sort. Check Mongo docs also.

Upvotes: 0

Related Questions