从另一个集合mongodb获取匹配和不匹配的计数

问题描述 投票:0回答:1

我的 mongodb 数据库中有两个集合。一个status列很常见。我需要基于 status 列的集合中的 匹配和不匹配计数。 我写了一些代码,但它只获取匹配的计数。

db.properties.aggregate([
    {
        $lookup: {
            from: "old_properties_data",
            localField: "identifier",
            foreignField: "identifier",
            as: "col2docs"
        }
    },
    
  
    {"$group" : {_id:"_id", count:{$sum:1}}}
])
mongodb mongodb-query lookup mongodb-lookup
1个回答
0
投票

您可以先按

$group
identifier
来获取总匹配数。然后您可以在$lookup中使用不相关的子查询来获取
old_properties_data
的总大小。最后执行
$subtract
以获得不匹配的总数。

db.properties.aggregate([
  {
    $lookup: {
      from: "old_properties_data",
      localField: "identifier",
      foreignField: "identifier",
      as: "matched"
    }
  },
  {
    $project: {
      identifier: 1,
      match_count: {
        $size: "$matched"
      }
    }
  },
  {
    "$group": {
      "_id": "$identifier",
      "total_match_count": {
        "$sum": "$match_count"
      }
    }
  },
  {
    "$lookup": {
      "from": "old_properties_data",
      "pipeline": [
        {
          "$count": "total"
        }
      ],
      "as": "total_count"
    }
  },
  {
    "$unwind": "$total_count"
  },
  {
    "$project": {
      total_match_count: 1,
      total_unmatched_count: {
        "$subtract": [
          "$total_count.total",
          "$total_match_count"
        ]
      }
    }
  }
])

这里是Mongo Playground供您参考。

© www.soinside.com 2019 - 2024. All rights reserved.