MongoDB Aggregation Query: Find Documents Having Count More Than 1
In MongoDB, you can use aggregation queries to perform complex data processing operations. One common task is to find documents that have a count greater than 1.
Since MongoDB version 5.0, one option is to use $setWindowFields
:
db.collection.aggregate([ {$setWindowFields: { "partitionBy": "$uniqueKey", "sortBy": {"cust_id": 1}, "output": { "count": { "$sum": 1, "window": {documents: ["unbounded", "unbounded"]} } } } }}, {$match: {count: {$gt: 1}}}, {$project: {_id: 0, "uniqueKey": 1, "cust_name": 1}} ])
See how it works on the playground example
This will prevent pushing all the documents with the same uniqueKey
into one big document.
Before mongoDB 5.0:
One option is to use $group
, but you need to use $push
on your $group
and $unwind
afterwards. This option may be problematic if you have many documents with the same uniqueKey