.find().sort().skip().limit()中.sort().skip().limit()的各种排列组合。
当sort,skip,limit一起使用时,无论其位置变化,总是先sort再skip,最后limit。
aggregate有管道流的性质, skip, s k i p , limit,$sort执行顺序跟位置一致,memos是collection。现在的顺序:match -> limit -> skip -> sort
db.memos.aggregate(
{ $match: { status: 'P' } },
{ $limit:5},
{ $skip:2},
{ $sort: { age : -1 } }
)
>>> from pymongo import MongoClient
>>> db = MongoClient().aggregation_example
>>> result = db.things.insert_many([{"x": 1, "tags": ["dog", "cat"]},
... {"x": 2, "tags": ["cat"]},
... {"x": 2, "tags": ["mouse", "cat", "dog"]},
... {"x": 3, "tags": []}])
>>> result.inserted_ids
[ObjectId('...'), ObjectId('...'), ObjectId('...'), ObjectId('...')]
>>> from bson.son import SON
>>> pipeline = [
... {"$unwind": "$tags"},
... {"$group": {"_id": "$tags", "count": {"$sum": 1}}},
... {"$sort": SON([("count", -1), ("_id", -1)])}
... ]
>>> import pprint
>>> pprint.pprint(list(db.things.aggregate(pipeline)))
[{u'_id': u'cat', u'count': 3},
{u'_id': u'dog', u'count': 2},
{u'_id': u'mouse', u'count': 1}]
document:
{
"_id" : ObjectId("57506d74c469888f0d631be6"),
"LOC" : "User001",
"COL" : [
{
"date" : "25/03/2016",
"number" : "Folio009",
"amount" : 100
},
{
"date" : "25/04/2016",
"number" : "Folio010",
"amount" : 100
}
] }
I assume you have a valid connection to MongoDB in Python.
The following code snippet will return a MongoDB cursor in result.
pipeline = [
{"$unwind": "$COL"},
{"$group": {"_id": "$LOC", "sum": {"$sum": "$COL.amount"}}}
]
cursor = collection.aggregate(pipeline)
Now you can convert cursor to list
result = list(cursor)
and if you print result’s value, you’ll get exactly the same result as in your Shell query.
[{u'sum': 200.0, u'_id': u'User001'}]
优化:
https://docs.mongodb.com/manual/reference/operator/aggregation/sort/
https://blog.csdn.net/suyu_yuan/article/details/51766483