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
Selected Reading
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" ] } Advertisements
