

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 that contains 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 } ] }
- Related Questions & Answers
- Find MongoDB documents that contains specific field?
- Find documents that contains specific field in MongoDB?
- Find document with array that contains a specific value in MongoDB
- MongoDB query to get only specific fields in nested array documents?
- MongoDB query to find documents whose array contains a string that is a substring of a specific word
- Get count of array elements from a specific field in MongoDB documents?
- Fetch specific multiple documents in MongoDB
- Find MongoDB documents where all objects in array have specific value?
- Find all documents that have two specific id's in an array of objects in MongoDB?
- Get specific elements from embedded array in MongoDB?
- MongoDB query to match documents that contain an array field
- MongoDB query to convert an array to a map of documents with n attributes?
- Get fields from multiple sub-documents that match a condition in MongoDB?
- Find MongoDB documents where elements of an array have a specific value?
- Querying on an array of objects for specific nested documents with MongoDB?
Advertisements