MongoDB: Removing an Object from an Array
In MongoDB, you can remove an object from an array embedded in a document using the $pull operator. If you wish to remove a specific object from an array, you need to provide a query that matches the exact object.
Consider the following document:
<code class="json">{ _id: 5150a1199fac0e6910000002, name: 'some name', items: [{ id: 23, name: 'item name 23' },{ id: 24, name: 'item name 24' }] }</code>
To remove the item with id: 23 from the items array, use the following command:
db.mycollection.update( { '_id': ObjectId("5150a1199fac0e6910000002") }, { $pull: { items: { id: 23 } } }, false, // Upsert true, // Multi );
This command updates the document by removing the item from the array. The query specifies the document using the _id field, and the $pull operator targets the items array. Within the $pull operation, you can specify a query to match the object to be removed. In this case, we match the object with id: 23.
Mongoose/Node.js Implementation
In Mongoose, you can remove an object from an array using the pull() method:
<code class="javascript">const Model = mongoose.model('Model', new mongoose.Schema({ items: [{ id: Number, name: String }] })); Model.update( { '_id': '5150a1199fac0e6910000002' }, { $pull: { items: { id: 23 } } }, { multi: true }, // Update all matching documents (err, result) => { if (!err) console.log(result); } );</code>
This code will remove the item with id: 23 from the items array of all documents that match the specified _id.
The above is the detailed content of How do I remove an object from an array in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!