remove array element mongodb code example

Example 1: mongodb remove from array

// query
db.stores.update(
    { },
    { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
    { multi: true }
)

// sample data
{
   _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 2: $pull mongoose

TemplateDoc.findOneAndUpdate(
    { userId: _id },
    { $pull: { templates: { _id: templateid } } },
    { new: true }
  )
    .then(templates => console.log(templates))
    .catch(err => console.log(err));

Tags:

Misc Example