
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get MongoDB Documents Containing Specific Attributes in Array
For this, you can use $and along with dot(.) notation. Let us first create a collection with documents −
>db.demo2.insertOne({"StudentInformation":[{"StudentName":"John","StudentAge":21},{"StudentName":"Mike","StudentAge":22}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e08b56e25ddae1f53b62219") } >db.demo2.insertOne({"StudentInformation":[{"StudentName":"Carol","StudentAge":19},{"StudentName":"Bob","StudentAge":18}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e08b58625ddae1f53b6221a") }
Following is the query to display all documents from a collection with the help of find() method −
> db.demo2.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e08b56e25ddae1f53b62219"), "StudentInformation" : [ { "StudentName" : "John", "StudentAge" : 21 }, { "StudentName" : "Mike", "StudentAge" : 22 } ] } { "_id" : ObjectId("5e08b58625ddae1f53b6221a"), "StudentInformation" : [ { "StudentName" : "Carol", "StudentAge" : 19 }, { "StudentName" : "Bob", "StudentAge" : 18 } ] }
Following is the query to get documents that contains specific attributes in array−
>db.demo2.find({$and:[{"StudentInformation.StudentName":"Carol"},{"StudentInformation.StudentName":"Bob"}]});
This will produce the following output −
{ "_id" : ObjectId("5e08b58625ddae1f53b6221a"), "StudentInformation" : [ { "StudentName" : "Carol", "StudentAge" : 19 }, { "StudentName" : "Bob", "StudentAge" : 18 } ] }
Advertisements