相关文章推荐
阳刚的青蛙  ·  NetCore使用DotNetCore.CA ...·  5 天前    · 
彷徨的充电器  ·  DAY11 MongoDB ...·  2 周前    · 
文武双全的足球  ·  Working with ...·  2 周前    · 
孤独的领结  ·  mongodb $lookup ...·  2 周前    · 
耍酷的爆米花  ·  python print ...·  9 月前    · 
沉稳的杨桃  ·  php json压缩-掘金·  1 年前    · 
活泼的铁链  ·  dynamic - Dynamically ...·  1 年前    · 

MongoDB elemMatch在查找管道中的应用?

0 人关注

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

部署_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 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))

这样做效果很好,但我怎样才能排除部署机器未被激活的结果?我觉得它必须放在项目中,但找不到一个有效的条件。希望得到任何帮助。

python
mongodb
mongoengine
James MV
James MV
发布于 2020-04-15
1 个回答
Ashh
Ashh
发布于 2020-04-15
已采纳
0 人赞同

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