问题描述
我有一个数据库
[
{
"_id": 1,"email": "amrit@gmail.com","status": "ACTIVE"
},{
"_id": 2,"email": "abc@gmail.com","status": "INACTIVE"
},{
"_id": 3,"email": "tut@gmail.com",{
"_id": 4,{
"_id": 5,{
"_id": 6,"email": "cat@gmail.com",]
现在,我想根据状态为活动和不活动的电子邮件查找该项目。 我已编写查询来查找类似的重复项。
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,因为它在数据库中既是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
}
}
])