聚合示例#
在MongoDB中有几种执行聚合的方法。这些示例使用map reduce和group方法介绍了新的聚合框架。
安装程序#
首先,我们将插入一些可以对其执行聚合的示例数据:
>>> 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('...')]
聚合框架#
此示例演示如何使用 aggregate()
方法来使用聚合框架。我们将执行一个简单的聚合来计算 tags
数组,跨越整个集合。为了实现这一点,我们需要将三个操作传递给管道。首先,我们需要放松 tags
数组,然后按标记分组并求和,最后按计数排序。
由于python字典没有维护您应该使用的顺序 SON
或 collections.OrderedDict
如果需要显式排序,例如“$sort”:
备注
聚合需要服务器版本 >= 2.1.0 .
>>> 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)))
[{'_id': 'cat', 'count': 3},
{'_id': 'dog', 'count': 2},
{'_id': 'mouse', 'count': 1}]
要为此聚合运行解释计划,请使用 PyMongoExplain ,一个适用于PyMongo的伴随库。它允许您通过提供几个方便的类来解释任何CRUD操作:
>>> from pymongoexplain import ExplainableCollection
>>> ExplainableCollection(collection).aggregate(pipeline)
{'ok': 1.0, 'queryPlanner': [...]}
或者,使用 command()
方法:
>>> db.command('aggregate', 'things', pipeline=pipeline, explain=True)
{'ok': 1.0, 'stages': [...]}
除了简单的聚合之外,聚合框架还提供投影功能来重塑返回的数据。使用投影和聚合,可以添加计算字段、创建新的虚拟子对象,并将子字段提取到结果的顶层。
参见
MongoDB的完整文档 aggregation framework