gpt4 book ai didi

python - Motor 1.1 中如何分组?

转载 作者:太空宇宙 更新时间:2023-11-03 15:47:38 27 4
gpt4 key购买 nike

我在当前项目中为 mongoDB 使用 Motor 异步客户端,并且我想使用像 group by 这样的聚合来进行查询。文档包含有关组的简短信息,但没有示例。

参数:

  1. key:分组依据的字段(参见上面的描述)
  2. 条件:要考虑的行规范(作为 find() 查询)规范)
  3. initial:聚合计数器对象的初始值
  4. reduce:聚合函数作为 JavaScript 字符串

我不知道初始参数和reduce(作为一个javascript字符串?)到底意味着什么。能举个例子吗?

最佳答案

Motor 的 group 方法采用与 PyMongo 相同的参数。调整 PyMongo group example至电机:

from bson.code import Code
from tornado import ioloop, gen
from motor import MotorClient

reducer = Code("""
function(obj, prev){
prev.count++;
}
""")

db = MotorClient().test


@gen.coroutine
def example():
yield db.things.remove({})
yield db.things.insert_many([
{'x': 1},
{'x': 2},
{'x': 2},
{'x': 3},
])

results = yield db.things.group(key={"x": 1}, condition={},
initial={"count": 0}, reduce=reducer)
for doc in results:
print(doc)


ioloop.IOLoop.current().run_sync(example)

打印:

{'count': 1.0, 'x': 1.0}
{'count': 2.0, 'x': 2.0}
{'count': 1.0, 'x': 3.0}

关于python - Motor 1.1 中如何分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41615636/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com