0

I have a document below:

{
  _id: ObjectId,
  name: 'String',
  description: 'String',
  articles: [
    { reference: ObjectId, title: 'String', digest: 'String', content: '...' },
    { reference: ObjectId, title: 'String', digest: 'String', content: '...' },
    { reference: ObjectId, title: 'String', digest: 'String', content: '...' },
    { reference: ObjectId, title: 'String', digest: 'String', content: '...' },
    ...
  ]
}

I want to only remove one specific article with ObjectId aid from this document. So I use the method with mongoose:

Model.update({
  _id: 'the document ObjectId',
}, {
  $pull: {
    articles: {
      $elemMatch: {
        reference: aid,
      },
    },
  },
});

the result is:

{n: 1, nModified: 1, ok: 1}

But the document change is different from what I expect:

{
  _id: ObjectId,
  name: 'String',
  description: 'String',
  articles: [],
}

I want to know why and how to remove one specific article as I expect.

1
  • 1
    You don't need to use $elemMatch try this $pull: {articles: {reference: aid}} Commented Mar 1, 2018 at 8:52

2 Answers 2

1

Try this

Model.update({
    _id: 'the document ObjectId',
}, {
    $pull: {
        articles: { "reference" : aid}
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the $pull operator for removing objects from the array in mongodb in the following way:

Model.findOneAndUpdate({_id: "the document ObjectId",{$pull: {arrayName: {"element Name": "element value"}}}})

Comments

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.