I have a collection with a bunch of documents, for example
{ items: [ObjectId1, ObjectId2, etc.] }
How do I run a query to identify which documents have duplicates? .distinct returns distinct values across the collection, but I want to be able to report on per document:
itemsitemsessentially, to understand which documents have duplicates in the items array.
You can use aggregation with $addToSet operator to have unique items in the set:
db.collection.aggregate([
{
"$unwind": "$items"
},
{
"$group": {
"_id": "$_id",
"items_cnt": {
"$sum": 1
},
"unique_items": {
"$addToSet": "$items"
}
}
},
{
"$project": {
"items_cnt": 1,
"unique_items_cnt": {
"$size": "$unique_items"
}
}
}
])