Execution order
. The find (). The sort (). The skip (), limit (). The sort (). The skip (), limit () of all kinds of permutation and combination. When sort,skip, and limit are used together, they always sort first, then skip, and then limit, regardless of their position.Copy the code
Skip,skip,limit,$sort if you want to change the order of execution by aggregate,skip, skip,limit,$sort The order is now match -> limit -> skip -> sort
db.memos.aggregate(
{ $match: { status: 'P'}}, {$limit:5},
{ $skip:2},
{ $sort: { age : -1}})Copy the code
Example 1: Aggregate
>>> 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('... ')]
Copy the code
>>> 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}]
Copy the code
Example 2 document:
{
"_id" : ObjectId("57506d74c469888f0d631be6"),
"LOC" : "User001"."COL": [{"date" : "25/03/2016"."number" : "Folio009"."amount" : 100
},
{
"date" : "25/04/2016"."number" : "Folio010"."amount" : 100}}]Copy the code
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)
Copy the code
Now you can convert cursor to list
result = list(cursor)
Copy the code
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'}]
Copy the code
Optimization:
https://docs.mongodb.com/manual/reference/operator/aggregation/sort/
https://blog.csdn.net/suyu_yuan/article/details/51766483
Copy the code