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 ] }