How to test whether unique index can be created in MongoDB?
You can use an aggregation query to check for duplicates before trying to create a unique index.

For example, if you want to create a unique index on fields a and b:


Insert some test data:

db.mycollection.insert([
    {a: 123, b: 456},
    {a: 123},
    {a: 123, b: 456},
    {c: 789 },
    {d: 321 }
])

Find documents with duplicate values:

db.mycollection.aggregate([

    // Group by the field combination you plan to add a unique index on
    { $group: {
        _id: { a: "$a", b: "$b"},
        count: { $sum: 1 }
    }},

    // Find any groups which are not unique (more than 1 matching document)
    { $match: {
        count: { "$gt": 1}
    }}
])

Aggregated output for the sample data above would indicate that there are two documents missing the expected fields a and b, and two documents with duplicate values of a and b:

{ "_id" : {  }, "count" : 2 }
{ "_id" : { "a" : 123, "b" : 456 }, "count" : 2 }



In this example I intentionally included some documents with expected fields missing, since those will be indexed as null values if you create a unique index. By default the unique requirement still applies even if one or more fields in the unique index is missing for a given document, because all documents in the collection are added to the index.

If you only want the field combination to be unique if both fields are present (or using some other criteria) you can create a Partial Index with Unique Constraint.