- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" ] }
Advertisements