Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
$whereoperator evaluates a JavaScript function for each document -
filter()creates a new array with elements matching the condition -
length > 1checks 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.
Advertisements
