0

Struggling with the use of $pop in a mongodb. Suppose I have the following collection:

`{_id:3
  name: "item 1",
  subdoc:{
            array:[
                     {id: "999",
                      name:"bar"
                     },
                     {id: "777",
                      name:"foo-bar"
                     }
                  ],
            anotherproperty: "foo"
         }
}`

Given it's id, I would like to remove an item from subdoc.array.

So for the document above, how can I remove the item with id="999", so that the only remaining item in subdoc.array would be the one with id="777"?

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
Adrian Taylor
  • 544
  • 1
  • 5
  • 14

1 Answers1

1

The $pop operator removes the first or last element of an array. Pass $pop a value of -1 to remove the first element of an array and 1 to remove the last element in an array.

I think it is better to use $pull to do it

> db.docs.update({name: 'item 1'}, {$pull: {'subdoc.array': {'id': '999'}}})
zangw
  • 43,869
  • 19
  • 177
  • 214