Skip to content Skip to sidebar Skip to footer

Pymongo Aggregation - Passing Python List For Aggregation

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': Obje

Solution 1:

You could try the following:

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]

Post a Comment for "Pymongo Aggregation - Passing Python List For Aggregation"