pymongo查询列表元素_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)

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.

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.

Is that possible?

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

解决方案

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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值