Reputation: 315
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
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
Reputation: 10071
Try this
Model.update({
_id: 'the document ObjectId',
}, {
$pull: {
articles: { "reference" : aid}
}
});
Upvotes: 1