- 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
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 ] }
- Related Articles
- Filter by several array elements in MongoDB?
- MongoDB query to filter by several array elements?
- How to filter array in subdocument with MongoDB?
- How to find specific array elements in MongoDB document with query and filter with range?
- How to filter documents based on an array in MongoDB?
- MongoDB query to filter object where all elements from nested array match the condition
- How to filter an array from all elements of another array – JavaScript?
- C# Program to filter array elements based on a predicate
- How do I push elements to an existing array in MongoDB?
- How to maintain the top count of array elements in MongoDB?
- How to project specific elements in an array field with MongoDB?
- Remove elements from array using JavaScript filter - JavaScript
- Move different elements to another array in MongoDB?
- How to filter an array in Java
- Filter query on array of embedded document with MongoDB?

Advertisements