Find document with array that contains a specific value in MongoDB



You can use find() method to find document with array that contains a specific value. The syntax is as follows:

db.yourCollectionName.find({"yourArrayFieldName":"yourValue"},.......N).pretty();

To understand the above syntax, let us create a collection with documents. The query to create a collection with documents is as follows:

>db.findSpecificValue.insertOne({"StudentId":1,"StudentName":"Larry","FavouriteSubject":["C","C++","Java"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c6e8996140577d89182b8d0") } >db.findSpecificValue.insertOne({"StudentId":2,"StudentName":"Larry","FavouriteSubject":["MongoDB","MySQL","SQL Server"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c6e89b1140577d89182b8d1") }

Display all documents from a collection with the help of find() method. The query is as follows:

> db.findSpecificValue.find().pretty();

The following is the output:

{    "_id" : ObjectId("5c6e8996140577d89182b8d0"),    "StudentId" : 1,    "StudentName" : "Larry",    "FavouriteSubject" : [       "C",       "C++",       "Java"    ] } {    "_id" : ObjectId("5c6e89b1140577d89182b8d1"),    "StudentId" : 2,    "StudentName" : "Larry",    "FavouriteSubject" : [       "MongoDB",       "MySQL",       "SQL Server"    ] }

Here is the query to find document with array that contains a specific value i.e. “MongoDB” for FavouriteSubject here:

> db.findSpecificValue.find({"FavouriteSubject":"MongoDB"}).pretty();

The following is the output:

{    "_id" : ObjectId("5c6e89b1140577d89182b8d1"),    "StudentId" : 2,    "StudentName" : "Larry",    "FavouriteSubject" : [       "MongoDB",       "MySQL",       "SQL Server"    ] }
Updated on: 2019-07-30T22:30:25+05:30

802 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements