Find all the non-distinct values of a field in MongoDB?

To find all non-distinct values of a field in MongoDB, use the aggregate() method with $group to count occurrences and $match to filter values that appear more than once.

Syntax

db.collection.aggregate([
    { $group: {
        "_id": "$fieldName",
        "count": { $sum: 1 }
    }},
    { $match: {
        "count": { $gt: 1 }
    }}
]);

Sample Data

db.findAllNonDistinctDemo.insertMany([
    { "UserName": "John", "UserAge": 28 },
    { "UserName": "Larry", "UserAge": 21 },
    { "UserName": "Larry", "UserAge": 23 },
    { "UserName": "David", "UserAge": 22 },
    { "UserName": "John", "UserAge": 26 },
    { "UserName": "Robert", "UserAge": 24 },
    { "UserName": "Robert", "UserAge": 25 },
    { "UserName": "Mike", "UserAge": 29 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("..."), ObjectId("..."), ...
    ]
}

View Sample Data

db.findAllNonDistinctDemo.find().pretty();
{ "_id": ObjectId("..."), "UserName": "John", "UserAge": 28 }
{ "_id": ObjectId("..."), "UserName": "Larry", "UserAge": 21 }
{ "_id": ObjectId("..."), "UserName": "Larry", "UserAge": 23 }
{ "_id": ObjectId("..."), "UserName": "David", "UserAge": 22 }
{ "_id": ObjectId("..."), "UserName": "John", "UserAge": 26 }
{ "_id": ObjectId("..."), "UserName": "Robert", "UserAge": 24 }
{ "_id": ObjectId("..."), "UserName": "Robert", "UserAge": 25 }
{ "_id": ObjectId("..."), "UserName": "Mike", "UserAge": 29 }

Find Non-Distinct Values

db.findAllNonDistinctDemo.aggregate([
    { $group: {
        "_id": "$UserName",
        "Counter": { $sum: 1 }
    }},
    { $match: {
        "Counter": { $gt: 1 }
    }}
]);
{ "_id": "Robert", "Counter": 2 }
{ "_id": "Larry", "Counter": 2 }
{ "_id": "John", "Counter": 2 }

How It Works

  • $group groups documents by UserName and counts occurrences using $sum: 1
  • $match filters groups where count is greater than 1 (non-distinct values)
  • The result shows field values that appear multiple times in the collection

Conclusion

Use aggregation pipeline with $group and $match to identify non-distinct field values. This approach efficiently finds duplicate values by counting occurrences and filtering results with count greater than 1.

Updated on: 2026-03-15T00:27:57+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements