- 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
How to select objects where an array contains only a specific field in MongoDB?
Let us first create a collection with documents −
> db.arrayContainOnlySpecificFieldDemo.insertOne( ... { ... "StudentName":"John", ... "StudentAge":21, ... "StudentTechnicalSubject":["C","Java","MongoDB"] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cc4921dac184d684e3fa26a") } > db.arrayContainOnlySpecificFieldDemo.insertOne( { "StudentName":"Carol", "StudentAge":23, "StudentTechnicalSubject":["MongoDB"] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cc49237ac184d684e3fa26b") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.arrayContainOnlySpecificFieldDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc4921dac184d684e3fa26a"), "StudentName" : "John", "StudentAge" : 21, "StudentTechnicalSubject" : [ "C", "Java", "MongoDB" ] } { "_id" : ObjectId("5cc49237ac184d684e3fa26b"), "StudentName" : "Carol", "StudentAge" : 23, "StudentTechnicalSubject" : [ "MongoDB" ] }
Following is the query to select objects where an array contains only a specific field −
> db.arrayContainOnlySpecificFieldDemo.find({"StudentTechnicalSubject":[ "MongoDB"]}).pretty();
This will produce the following output −
{ "_id" : ObjectId("5cc49237ac184d684e3fa26b"), "StudentName" : "Carol", "StudentAge" : 23, "StudentTechnicalSubject" : [ "MongoDB" ] }
Advertisements
To Continue Learning Please Login
Login with Google