- 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 filter array elements in MongoDB?
You can use $setIntersection operator along with aggregate framework to filter array elements in MongoDB. Let us first create a collection with documents −
> db.filterArrayElementsDemo.insertOne( { "Scores": [10,45,67,78,90,98,99,92] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2d582b64f4b851c3a13c8") }
Following is the query to display all documents from a collection with the help of find() method −
> db.filterArrayElementsDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd2d582b64f4b851c3a13c8"), "Scores" : [ 10, 45, 67, 78, 90, 98, 99, 92 ] }
Following is the query to filter array elements −
> db.filterArrayElementsDemo.aggregate([ ... { $match : { ... _id: ObjectId("5cd2d582b64f4b851c3a13c8") ... }}, ... { $project: { ... Scores: { ... $setIntersection: ['$Scores', [10,98,99]] ... } ... }} ... ]);
This will produce the following output −
{ "_id" : ObjectId("5cd2d582b64f4b851c3a13c8"), "Scores" : [ 10, 98, 99 ] }
Advertisements