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
Find the exact match in array without using the $elemMatch operator in MongoDB?
To find an exact match in an array without using the $elemMatch operator in MongoDB, use the $eq operator to match the entire array structure or query specific array elements directly.
Syntax
// Match entire array exactly
db.collection.find({"arrayField": {$eq: ["value1", "value2"]}});
// Match specific element in array
db.collection.find({"arrayField": "specificValue"});
Sample Data
db.equalDemo.insertMany([
{_id: 1, "StudentFriendNames": ["John", "Carol", "Sam"]},
{_id: 2, "StudentFriendNames": null},
{_id: 3, "StudentFriendNames": ["Carol"]},
{_id: 4, "StudentFriendNames": ["Sam"]}
]);
{ "_id" : 1, "StudentFriendNames" : [ "John", "Carol", "Sam" ] }
{ "_id" : 2, "StudentFriendNames" : null }
{ "_id" : 3, "StudentFriendNames" : [ "Carol" ] }
{ "_id" : 4, "StudentFriendNames" : [ "Sam" ] }
Method 1: Exact Array Match Using $eq
Find documents where the array exactly matches ["Carol"] ?
db.equalDemo.find({"StudentFriendNames": {$eq: ["Carol"]}});
{ "_id" : 3, "StudentFriendNames" : [ "Carol" ] }
Method 2: Direct Element Query
Find documents where the array contains "Carol" (without specifying exact structure) ?
db.equalDemo.find({"StudentFriendNames": "Carol"});
{ "_id" : 1, "StudentFriendNames" : [ "John", "Carol", "Sam" ] }
{ "_id" : 3, "StudentFriendNames" : [ "Carol" ] }
Key Differences
-
$eqmatches the entire array structure exactly (order and length matter) - Direct querying matches arrays containing the specified value
- Both methods avoid
$elemMatchfor simpler array matching scenarios
Conclusion
Use $eq for exact array matches or direct field queries for element containment. These alternatives to $elemMatch work well when you need simple array matching without complex conditions.
Advertisements
