我有一个文档引用了另一个文档,我想联接这些文档,并根据子文档中数组的内容进行过滤:
deployment_machine文档:
{
"_id": 1,
"name": "Test Machine",
"machine_status": 10,
"active": true
}
machine_status文档:
{
"_id": 10,
"breakdown": [
{
"status_name": "Rollout",
"state": "complete"
},
{
"status_name": "Deploying",
"state": "complete"
}
]
}
我使用的是Mongo3.6,在查找和管道方面取得了混合的成功,下面是我在传递给聚合函数的python MongoEngine中使用的对象:
pipeline = [
{'$match': {'breakdown': {'$elemMatch': {'status_name': 'Rollout'}}}},
{'$lookup':
{
'from': 'deployment_machine',
'let': {'status_id': '$_id'},
'pipeline': [
{'$match':
{'$expr':
{'$and': [
{'$eq': ['$machine_status', '$$status_id']},
]},
}
}
],
'as': 'result',
},
},
{'$project': {
'breakdown': {'$filter': {
'input': '$breakdown',
'as': 'breakdown',
'cond': {'$eq': ['$$breakdown.status_name', 'Rollout']}
}}
}},
]
result = list(MachineStatus.objects.aggregate(*pipeline))
这很有效,但我如何排除部署计算机未处于活动状态的结果呢?我觉得它必须在项目中进行,但找不到一个可以工作的条件。感谢您的帮助。
发布于 2020-04-15 03:13:58
您可以在$lookup
管道中添加更多条件
pipeline = [
{ $match: { breakdown: { $elemMatch: { status_name: "Rollout" } } } },
{
$lookup: {
from: "deployment_machine",
let: { status_id: "$_id" },
pipeline: [
{
$match: {
$expr: { $eq: ["$machine_status", "$$status_id"] },
active: false
}
}
],
as: "result",
}
},
{
$project: {
breakdown: {
$filter: {
input: "$breakdown",
as: "breakdown",
cond: { $eq: ["$$breakdown.status_name", "Rollout"] },
}
}
}
}
];
https://stackoverflow.com/questions/61215253
复制相似问题