Search code examples
node.jsmongodbnode-mongodb-native

How would I remove an item from an array with mongo?


I'd like to atomically remove an item from an array. I was looking at using findAndModify but I'm not sure how that would work. Any direction on how to atomically remove an item from an array in a doc would be much appreciated!

Thanks!


Solution

  • You can use the $pull operator in an update or findAndModify for that:

    db.collection.update({_id: id}, {$pull: {foo: 'bar'}});
    

    This would remove the 'bar' element from the foo array field of the document matching {_id: id}.