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:
{
_id: 5150a1199fac0e6910000002,
name: 'some name',
items: [{
id: 23,
name: 'item name 23'
},{
id: 24,
name: 'item name 24'
}]
}
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:
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); }
);
This code will remove the item with id: 23 from the items array of all documents that match the specified _id.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3