r/MongoDB_Official • u/Aromatic-Departure17 • 4d ago
Showcase Finding duplicate MongoDB values before adding a unique index
I’m building KeplerGrid, a desktop MongoDB client. Here’s a small check I run before adding a regular single-field unique index to a collection.
In Aggregation → JSON, run this pipeline. It groups orders by external_id and keeps groups with more than one document.
[
{ "$group": {
"_id": { "$ifNull": ["$external_id", null] },
"count": { "$sum": 1 }
} },
{ "$match": { "count": { "$gt": 1 } } },
{ "$sort": { "count": -1, "_id": 1 } }
]In the screenshot, two of three synthetic orders share ERP-100. Switch to Documents and run { "external_id": "ERP-100" } to inspect both originals. Check which key each record should have before editing either. A null group can also flag a conflict because a regular single-field unique index uses the same key for explicit nulls and missing fields.
After resolving the conflict, rerun the pipeline and confirm it returns no duplicate groups. Then open Indexes, enter { "external_id": 1 }, select Unique values, and click Create index. Verify that the new index shows UNIQUE.
Full walkthrough and three practice documents

1
u/Gullible-Put-7358 4d ago
Neat!
One additional test to confirm that
$ifNulltreats bothnullor missing fields asnull.Input:
The
$groupstage also treats bothnullor missing fields asnull; thus,$ifNullis not needed. This will do:Also, curious: how do you then go back after obtaining these aggregate results and dedup, if applicable? One idea is to also expose the
_idof the docs with dups to identify the culprits later on.Here's a Playground example link
Cheers
di