Tutorialspoint

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


1 Answer
Smita Kapse

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" ] }

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.