0

Say you have an array in MongoDB: [a,b,c,a,d]

How do you remove f.e. the first a, but not the second. Otherwise put: the operation should finish directly after deleting the first a, so it does not delete the second a. Also these arrays change all the time, so you can't know where the a is beforehand.

  • Possible duplicate of [MongoDB, remove object from array](http://stackoverflow.com/questions/15641492/mongodb-remove-object-from-array) – dvlsg Dec 23 '16 at 17:25
  • Did [my answer](https://stackoverflow.com/questions/41305507/how-to-remove-the-first-matching-instance-from-an-array-using-mongoose/41305655#41305655) below answer your question? If then you may consider [accepting the answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) so that other people who search for this topic could see that it has an accepted answer. – rsp Dec 27 '16 at 18:23

1 Answers1

0

You cannot do it in one request.

You should be able to use update to set the first element (and not all of them) to null with something like this

x.update({_id: "xxx"}, {$unset: {"field.$": "a"}})

but then you will have to remove the null with:

x.update({}, {$pull: {field: null}})

This is not tested. Of course change field to your field name.

rsp
  • 107,747
  • 29
  • 201
  • 177