Removing an Object from an Array in MongoDB
When dealing with documents that contain arrays, it may be necessary to remove specific objects from them. This is commonly seen with documents that store a list of items or similar entries. In MongoDB, there is a designated operator, known as $pull, specifically designed for this purpose.
The example provided illustrates a document with an array of items. The goal is to remove the item object with id equal to 23. The initial attempt to use $pull is incorrect, as it attempts to match on the id field directly within the $pull statement, which is not the correct syntax.
To successfully remove the desired object, the correct query is:
db.mycollection.update( { '_id': ObjectId("5150a1199fac0e6910000002") }, { $pull: { items: { id: 23 } } }, false, // Upsert true, // Multi );
This query specifies that it wants to update the document with the given _id, and in that update, it applies the $pull operator to the items array, matching each array element with an id of 23.
For those using Mongoose/Node.js, the equivalent code snippet is:
<code class="javascript">Model.updateOne( { '_id': ObjectId("5150a1199fac0e6910000002") }, { $pull: { items: { id: 23 } } }, function(err, result) { // Handle error or result } );</code>
The above is the detailed content of How to Remove an Object from an Array in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!