我的 mongodb 数据库中有两个集合。一个status列很常见。我需要基于 status 列的集合中的 匹配和不匹配计数。 我写了一些代码,但它只获取匹配的计数。
db.properties.aggregate([
{
$lookup: {
from: "old_properties_data",
localField: "identifier",
foreignField: "identifier",
as: "col2docs"
}
},
{"$group" : {_id:"_id", count:{$sum:1}}}
])
您可以先按
$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供您参考。