- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Query to retrieve multiple items in an array in MongoDB?
To retrieve multiple items in an array, use aggregate framework. Let us first create a collection with documents −
> db.retrieveMultipleDemo.insertOne( ... { ... "UserDetails": ... [ ... { "_id": "101", "UserName":"John", "UserAge": 23 }, ... { "_id": "102", "UserName":"Carol", "UserAge": 21 }, ... { "_id": "103", "UserName":"David", "UserAge": 23}, ... { "_id": "104", "UserName":"Sam", "UserAge": 25} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd40c85edc6604c74817cf0") }
Following is the query to display all documents from a collection with the help of find() method −
> db.retrieveMultipleDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd40c85edc6604c74817cf0"), "UserDetails" : [ { "_id" : "101", "UserName" : "John", "UserAge" : 23 }, { "_id" : "102", "UserName" : "Carol", "UserAge" : 21 }, { "_id" : "103", "UserName" : "David", "UserAge" : 23 }, { "_id" : "104", "UserName" : "Sam", "UserAge" : 25 } ] }
Following is the query to retrieve multiple items in an array −
> db.retrieveMultipleDemo.aggregate([ ... {$unwind:"$UserDetails"}, ... {$match:{"UserDetails._id":{$in:myIds},"UserDetails.UserAge":23}}, ... {$group:{"_id":"_id","UserDetails":{$push:"$UserDetails"}}}, ... {$project:{"_id":0,"UserDetails":1}} ... ]);
This will produce the following output −
{ "UserDetails" : [ { "_id" : "101", "UserName" : "John", "UserAge" : 23 }, { "_id" : "103", "UserName" : "David", "UserAge" : 23 } ] }
- Related Articles
- MongoDB find by multiple array items using $in?
- MongoDB find by multiple array items?
- Which MongoDB query finds same value multiple times in an array?
- Retrieve the position in an Array in MongoDB?
- MongoDB query to pull multiple values from array
- MongoDB query to find documents having two values in an array conforming to multiple criteria?
- How to query all items in MongoDB?
- What kind of MongoDB query finds same value multiple times in an array?
- MongoDB query to find value in array with multiple criteria (range)
- MongoDB query to access an object in an array
- MongoDB query to replace value in an array?
- How to get items from an object array in MongoDB?
- MongoDB query to find multiple matchings inside array of objects?
- Update multiple elements in an array in MongoDB?
- Count the number of items in an array in MongoDB?

Advertisements