Let's say I had a Schema called MyDoc with field key. These were my documents:
[
{
"key": 1
},
{
"key": 2
},
{
"key": 2
},
{
"key": 3
},
{
"key": 3
},
{
"key": 3
},
{
"key": 4
}
]
With mongoose, I want to find documents that have a unique key value. AKA return all docs where no other docs have its key value.
Above, there are multiple docs with 2 and 3. One document each has a value of 1 and 4. So in this example, I want to return only the document with 1 and 4.
CodePudding user response:
One options is via aggregation group:
db.collection.aggregate([
{
$group: {
_id: "$key",
cnt: {
$sum: 1
}
}
},
{
$match: {
cnt: {
$eq: 1
}
}
},
{
$project: {
key: "$_id",
_id: 0
}
}
])
Stages explained:
- Group by key to count() the duplicates
- Match only those that have no duplicates
- Project only the needed keys
