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"

}

1

1 Answer 1

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"}}}
                )
Sign up to request clarification or add additional context in comments.

2 Comments

But I just have the _id of item2 doc and not the actual values of item2.
Have you tried passing _id to the $pull operator ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.