我正在尝试从python中的mongodb集合中选择一些数据,这里有一些示例数据:
[{"id":1, "planned_timestamp":1512728425, "executed_timestamp":0, "owner":1, "action_type": "read", "action_params":"book A"},
{"id":2, "planned_timestamp":1512728430, "executed_timestamp":0, "owner":1, "action_type": "read", "action_params":"book B"},
{"id":3, "planned_timestamp":1512728435, "executed_timestamp":0, "owner":2, "action_type": "read", "action_params":"book C"}]
我想选择"executed_timestamp":0
,"planned_timestamp"
低于timestamp变量的所有任务,我希望得到如下结果:
[{"owner":1, "tasks": [{"id":1,"planned_timestamp":1512728425,"action_type": "read","action_params":"book A"},{"id":1,"planned_timestamp":1512728430,"action_type": "read","action_params":"book B"}]},
{"owner":2, "tasks": [{"id":3,"planned_timestamp":1512728435,"action_type": "read","action_params":"book C"}]}]
我目前与pymongo的请求是:
r = db.task_queue.aggregate(
[
{ "$group" : { "_id" : "$agent_id", "tasks": { "$push": "$$ROOT" } } }
]
)
答案 0 :(得分:0)
什么是agent_id
?
您需要的是$match
。试试这个。
timestamp = 1500000000
r = db.task_queue.aggregate(
[
{"$match": {"$and": [
{
"executed_timestamp": {"$eq": 0},
"planned_timestamp": {"$lte": timestamp}
}
]}},
{"$group" : { "_id" : "$owner", "tasks": { "$push": "$$ROOT" } } },
{"$project":
{
"_id": 0,
"owner": "$_id.owner",
"tasks": 1
}}
]
)