Find the exact match in array without using the $elemMatch operator in MongoDB?


As an alternative, use the $eq operator. Let us first create a collection with documents −

> db.equalDemo.insertOne({_id:1,"StudentFriendNames":["John","Carol","Sam"]});
{ "acknowledged" : true, "insertedId" : 1 }
> db.equalDemo.insertOne({_id:2,"StudentFriendNames":null});
{ "acknowledged" : true, "insertedId" : 2 }
> db.equalDemo.insertOne({_id:3,"StudentFriendNames":["Carol"]});
{ "acknowledged" : true, "insertedId" : 3 }
> db.equalDemo.insertOne({_id:4,"StudentFriendNames":["Sam"]});
{ "acknowledged" : true, "insertedId" : 4 }

Following is the query to display all documents from a collection with the help of find() method −

> db.equalDemo.find();

This will produce the following output −

{ "_id" : 1, "StudentFriendNames" : [ "John", "Carol", "Sam" ] }
{ "_id" : 2, "StudentFriendNames" : null }
{ "_id" : 3, "StudentFriendNames" : [ "Carol" ] }
{ "_id" : 4, "StudentFriendNames" : [ "Sam" ] }

Following is the query to get the exact match using $eq −

> db.equalDemo.find({"StudentFriendNames":{$eq:["Carol"]}});

This will produce the following output −

{ "_id" : 3, "StudentFriendNames" : [ "Carol" ] }

Updated on: 30-Jul-2019

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements