weichao.x
weichao.x

Reputation: 315

Remove an element in an Object Array in Mongodb?

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.

Upvotes: 0

Views: 194

Answers (2)

Naimish Kher
Naimish Kher

Reputation: 294

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"}}}})

Upvotes: 1

Rahul Sharma
Rahul Sharma

Reputation: 10071

Try this

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

Upvotes: 1

Related Questions