I'm joining a document using aggregation in Mongo 3.6 and filtering results based on the elements inside one of the arrays. This is working ok except I want to filter out results where the filtered array is empty.
deployment_machine document:
{
"_id": 1,
"name": "Test Machine",
"machine_status": 10,
"active": true
}
machine_status document:
{
"_id": 10,
"breakdown": [
{
"status_name": "Rollout",
"state": "complete"
},
{
"status_name": "Deploying",
"state": "complete"
}
]
}
The object I'm using in the python MongoEngine being passed to the aggregate function:
pipeline = [
{'$lookup':
{
'from': 'deployment_machine',
'let': {'status_id': '$_id'},
'pipeline': [
{'$match': {
'$expr': {'$eq': ['$system_status', '$$status_id']},
'active': True
},
}
],
'as': 'result',
},
},
{'$project': {
'breakdown': {'$filter': {
'input': '$breakdown',
'as': 'breakdown',
'cond': {'$eq': ['$$breakdown.status_name', 'Rollout']}
}}
}},
]
result = list(MachineStatus.objects.aggregate(*pipeline))
The result looks like this:
[
{"_id": 1,"name": "Test Machine","machine_status": 10, "active": true, "breakdown": [{"status_name": "Rollout", "state": "complete"}]},
{"_id": 2,"name": "Another Machine","machine_status": 11, "active": true, "breakdown": []}
]
I want to remove the result where breakdown is an empty array. Should I use a final match condition or can I do this in the project?