MongoDB 查找管道中的 elemMatch?

MongoDB elemMatch in lookup pipeline?

我有一个引用另一个文档的文档,我想加入这些文档并根据子文档中数组的内容进行过滤:

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"
    }
  ]
}

我正在使用 Mongo 3.6,并且在查找和管道方面取得了不同程度的成功,这是我在 python Mongo 引擎中使用的对象被传递给聚合函数:

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))

这很好用,但我如何排除部署计算机不活动的结果?我觉得它必须进入项目,但找不到可行的条件。任何帮助表示赞赏。

您可以在 $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"] },
        }
      }
    }
  }
];