在MongoDB中查找重复项,同时比较这些重复项中的某些字段



我有一个数据库

[
{
"_id": 1,
"email": "amrit@gmail.com",
"status": "ACTIVE"
},
{
"_id": 2,
"email": "abc@gmail.com",
"status": "INACTIVE"
},
{
"_id": 3,
"email": "tut@gmail.com",
"status": "ACTIVE"
},
{
"_id": 4,
"email": "amrit@gmail.com",
"status": "INACTIVE"
},
{
"_id": 5,
"email": "tut@gmail.com",
"status": "ACTIVE"
},
{
"_id": 6,
"email": "cat@gmail.com",
"status": "ACTIVE"
},

]

现在我想根据电子邮件找到该项目,其状态为ACTIVE和INACTIVE。我编写查询是为了查找类似的重复项。

db.getCollection(‘employees’).aggregate([
{$group: {
_id: {email: “$email”},
uniqueIds: {$addToSet: “$_id”},
count: {$sum: 1}
}
},
{$match: {
count: {“$gt”: 1}
}
}
], {allowDiskUse:true });

此返回两者tut@gmail.com和amrit@gmail.com但我只想amrit@gmail.com因为它在db中同时为ACTIVE和INACTIVE。结果应该看起来像

{
"_id": {
"email": "amrit@gmail.com"
},
"uniqueIds": [
4,
1
]
}

尝试以下查询。

db.getCollection("employees").aggregate([
{
$group: {
_id: {
email: "$email"
},
uniqueIds: {
$addToSet: "$_id"
},
status: {
$addToSet: "$status"
}
}
},
{
$match: {
status: {
"$all": [
"ACTIVE",
"INACTIVE"
]
}
}
},
{
$project: {
status: 0
}
}
])

这里是MongoPlayground。

最新更新