Home >Web Front-end >JS Tutorial >How to Remove a Specific Object from an Array in MongoDB?
Problem:
In MongoDB, how do you extract a specific object from an array embedded within a document? In the example document, we want to remove the object with id: 23 from the items array.
Solution:
To achieve this, use the $pull operator with a more specific query to match the desired object within the array.
MongoDB Query:
db.mycollection.update( { '_id': ObjectId("5150a1199fac0e6910000002") }, { $pull: { items: { id: 23 } } }, false, // Upsert true // Multi );
Explanation:
Node.js/Mongoose:
In Mongoose, you can use the following query:
<code class="javascript">MyModel.findOneAndUpdate( { '_id': '5150a1199fac0e6910000002' }, { $pull: { items: { id: 23 } } }, { multi: true } );</code>
Note: MongoDB 3.6 also supports the $elemMatch operator in conjunction with $pull for more complex filtering within arrays.
The above is the detailed content of How to Remove a Specific Object from an Array in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!