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

  • $eq matches the entire array structure exactly (order and length matter)
  • Direct querying matches arrays containing the specified value
  • Both methods avoid $elemMatch for 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.

Updated on: 2026-03-15T01:30:32+05:30

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements