remove an element from an array mongodb code example
Example 1: how to delete subdocument array object mongodb
db.getCollection('profilesservices').updateOne({_id: ObjectId("60391a9eefdb7c17bd84c0b1")},
{
$pull: { "volunteerExperiences": {_id: ObjectId("60392e7595bb2d87689aca62")} }
}
)
Example 2: mongodb remove from array
db.stores.update(
{ },
{ $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
{ multi: true }
)
{
_id: 1,
fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ],
vegetables: [ "carrots", "celery", "squash", "carrots" ]
}
{
_id: 2,
fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]
}
Example 3: $pull mongoose
TemplateDoc.findOneAndUpdate(
{ userId: _id },
{ $pull: { templates: { _id: templateid } } },
{ new: true }
)
.then(templates => console.log(templates))
.catch(err => console.log(err));
Example 4: Mongodb Remove array element by index
db.example.update({}, [
{$set: {field: {
$concatArrays: [
{$slice: ["$field", P]},
{$slice: ["$field", {$add: [1, P]}, {$size: "$field"}]}
]
}}}
]);