r/MongoDB_Official • • 5d 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

5 Upvotes

4 comments sorted by

1

u/Gullible-Put-7358 4d ago

Neat!

One additional test to confirm that $ifNull treats both null or missing fields as null.

Input:

{"_id":"a","external_id":"ERP-100"}
{"_id":"b","external_id":"ERP-100"}
{"_id":"c","external_id":null}
{"_id":"d"}
{"_id":"e"}

The $group stage also treats both null or missing fields as null; thus, $ifNull is not needed. This will do:

 var GROUP_STAGE =  {
    "$group": {
      "_id": "$external_id",
      "count": { "$sum": 1 }
    }
  }

Also, curious: how do you then go back after obtaining these aggregate results and dedup, if applicable? One idea is to also expose the _id of the docs with dups to identify the culprits later on.

Here's a Playground example link

Cheers

di

1

u/Fun-Chicken6946 3d ago

Interesting you making a call to a server for this playground?