- 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 pull even numbers from an array in MongoDB?
Use $mod to get the even numbers and pull them from the array. Let us first create a collection with documents −
>db.pullEvenNumbersDemo.insertOne({"AllNumbers":[101,102,104,106,108,109,110,112,14,17,18,21]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd45b072cba06f46efe9eea") }
Following is the query to display all documents from the collection with the help of find() method −
> db.pullEvenNumbersDemo.find().pretty();
This will produce the following output −
{ "AllNumbers" : [ 102, 104, 106, 108, 109, 110, 112, 14, 17, 18, 21 ] }
Following is the query to pull even numbers from an array in MongoDB −
> db.pullEvenNumbersDemo.updateMany({},{ "$pull": { "AllNumbers": { "$mod": [ 2, 0 ] } } } ); { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
Let us check all the documents once again −
> db.pullEvenNumbersDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd45b072cba06f46efe9eea"), "AllNumbers" : [ 101, 109, 17, 21 ] }
- Related Articles
- Pull multiple objects from an array in MongoDB?
- How to pull all elements from an array in MongoDB without any condition?
- How to pull value from array of ObjectIDs in MongoDB?
- MongoDB query to pull multiple values from array
- How to use MongoDB $pull to delete documents within an Array?
- Removing an array element from MongoDB collection using update() and $pull
- How to pull an array element (which is a document) in MongoDB?
- MongoDB query to pull array element from a collection?
- How to pull distinct values from an array in java?
- Finding even length numbers from an array in JavaScript
- Pull an element in sub of sub-array in MongoDB?
- Returning an array containing last n even numbers from input array in JavaScript
- C++ code to decrease even numbers in an array
- How to find the Odd and Even numbers in an Array in java?
- How to delete element from an array in MongoDB?

Advertisements