0

I m trying to completely remove a document from mongodb collection having an array of documents as property. I have used $pull and $unset , which successfully find and remove the values within a doc by making them null but the doc still exists.

Eg .Original document

{
    _id: 6452725 gsjhye73636,
    ItemsArray: [{
            _id: 757264 gsjfgs685,
            ItemName: "item1",
            ItemValue: "value1"
        },
        {
            _id: 757264 gsjfgs686,
            ItemName: "item2",
            ItemValue: "value2"
        },
        {
            _id: 757264 gsjfgs687,
            ItemName: "item3",
            ItemValue: "value3"
        }
    ],
    OtherProp: "some value"
}

After applying $pull and $unset for removing item2 document.

{
  _id: 6452725 gsjhye73636,
  ItemsArray: [{
          _id: 757264 gsjfgs685,
          ItemName: "item1",
          ItemValue: "value1"
      },
      {
          _id: 757264 gsjfgs686,
          ItemName: null,
          ItemValue: null
      },
      {
          _id: 757264 gsjfgs687,
          ItemName: "item3",
          ItemValue: "value3"
      }
  ],
  OtherProp: "some value"
}

What I want is this:

  {
  _id: 6452725 gsjhye73636,
  ItemsArray: [{
          _id: 757264 gsjfgs685,
          ItemName: "item1",
          ItemValue: "value1"
      },
      {
          _id: 757264 gsjfgs687,
          ItemName: "item3",
          ItemValue: "value3"
      }
  ],
  OtherProp: "some value"

}

s7vr
  • 73,656
  • 11
  • 106
  • 127
Nikhil
  • 467
  • 10
  • 22
  • Possible duplicate of [Using MongoDB $pull to delete documents within an Array](http://stackoverflow.com/questions/15121758/using-mongodb-pull-to-delete-documents-within-an-array) – s7vr Apr 22 '17 at 17:47

1 Answers1

0

There is a very handy example at the end of the official documentation for $pull operator.

For your case, the query would be:

db.mycol.update({}, 
                {$pull: {"ItemsArray": {"ItemName": "item2"}}}
                )
phreeLynx
  • 65
  • 3