What kind of MongoDB query finds same value multiple times in an array?

To find documents where the same value appears multiple times in an array, use the $where operator with JavaScript functions to filter and count duplicate values within array elements.

Syntax

db.collection.find({
    "$where": function() {
        return this.arrayField.filter(function(element) {
            return element.field == targetValue;
        }).length > 1;
    }
});

Sample Data

db.demo188.insertMany([
    {
        "ListOfData": [
            {"Data": 100},
            {"Data": 200},
            {"Data": 100}
        ]
    },
    {
        "ListOfData": [
            {"Data": 100},
            {"Data": 200},
            {"Data": 300}
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3ad1c203d395bdc21346bd"),
        ObjectId("5e3ad1c203d395bdc21346be")
    ]
}

Display All Documents

db.demo188.find();
{ "_id": ObjectId("5e3ad1c203d395bdc21346bd"), "ListOfData": [{ "Data": 100 }, { "Data": 200 }, { "Data": 100 }] }
{ "_id": ObjectId("5e3ad1c203d395bdc21346be"), "ListOfData": [{ "Data": 100 }, { "Data": 200 }, { "Data": 300 }] }

Find Documents with Duplicate Values

The following query finds documents where the value 100 appears multiple times in the array ?

db.demo188.find({
    "$where": function() {
        return this.ListOfData.filter(function(d) {
            return d.Data == 100;
        }).length > 1;
    }
});
{ "_id": ObjectId("5e3ad1c203d395bdc21346bd"), "ListOfData": [{ "Data": 100 }, { "Data": 200 }, { "Data": 100 }] }

How It Works

  • The $where operator evaluates a JavaScript function for each document
  • filter() creates a new array with elements matching the condition
  • length > 1 checks if more than one occurrence exists
  • Only documents with duplicate values in the array are returned

Conclusion

Use $where with JavaScript filter functions to identify documents containing duplicate values within arrays. This approach counts occurrences and returns only documents where the target value appears multiple times.

Updated on: 2026-03-15T01:41:18+05:30

478 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements