Pymongo聚合-传递用于聚合的python列表 [英] Pymongo aggregation - passing python list for aggregation

查看:359
本文介绍了Pymongo聚合-传递用于聚合的python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果所有元素都在查询中进行了硬编码,这是我尝试根据时间戳(每日)执行汇总.

Here is my attempt at performing the aggregation (day-wise) based on timestamp if all the elements are hardcoded inside the query.

pipe = [ 
{
     "$match": { 
        "cid": ObjectId("57fe39972b8dbc1387b20913")
        }
    },
{
    "$project":
    {

        "animal_dog": "$animal.dog",
        "animal_dog_tail": "$animal.dog.tail",
        "animal_cat": "$animal.cat",
        "tree": "$fruits",
        "day": {"$substr": ["$timestamp",  0, 10]} 
        }},
{ 
"$group":
    {
    "_id" : "$day",
    "animal_dog" : {"$sum": "$animal_dog"},
    "animal_dog_tail": {"$sum": "$animal_dog_tail"}, 
    "animal_cat": {"$sum": "$animal_cat"}, 
    "tree": {"$sum": "$tree"}, 
    "fruits": {"$sum": "$fruits"},

}} ]

output = dailycollection.aggregate(pipeline = pipe)

假设我的mongo-collection具有完全相同的嵌套结构,如何传递带有相应元素的python_list以便基于时间戳进行汇总? 假设我的Python列表包含以下元素:

Assuming that I have a mongo-collection having the exact same nested structure, how do I pass a python_list with the respective elements for aggregating based on timestamp? Let's say my Python list has elements like this:

key_list = animal.dog, animal.dog.tail, animal.cat, tree, fruits, timestamp.

key_list = animal.dog, animal.dog.tail, animal.cat, tree, fruits, timestamp.

我想将此列表传递到我刚才编写的查询中,而无需对每个元素进行硬编码.我想对元素执行projection$sum$group,而无需像在上述查询中那样对它们进行硬编码.我想在$project$group阶段简单地遍历python列表.

I would like to pass this list into the query I just wrote above without hardcoding each of the elements. I would like to perform projection, $sum, $group for the elements without hardcoding them as I did in the aforementioned query. I would like to simply iterate through the python list during $project and $group stage.

有可能吗?

还有如何确保输出查询也保留相同的嵌套格式而又不损失深度?

And also how do I ensure that the output query also preserves the same nested-format without losing depth?

推荐答案

您可以尝试以下操作:

key_list =  ["animal.dog", "animal.dog.tail", "animal.cat", "tree", "fruits", "timestamp"]
match = { "$match": { "cid": ObjectId("57fe39972b8dbc1387b20913") } }
project = { "$project": {} }
group = { "$group": {} }

for item in key_list:
    if item == "timestamp":
        project["$project"]["day"] = { "$substr": ["$"+item,  0, 10] }
        group["$group"]["_id"] = "$day"
        break
    sum = {"$sum": ""}
    sum["$sum"] = "$"+item.replace(".", "_")
    project["$project"][item.replace(".", "_")] = "$"+item
    group["$group"][item.replace(".", "_")] = sum

pipeline = [match, project, group]

这篇关于Pymongo聚合-传递用于聚合的python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆