Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb remove document if array count zero after $pull in a single query

I have a requirement where my comments schema looks like the following

{
  "_id": 1,
  "comments": [
    { "userId": "123", "comment": "nice" },
    { "userId": "124", "comment": "super"}
  ]
}

I would like to pull the elements based on the userId field. I am doing the following query

comments.update({},{$pull:{comments:{userId:"123"}}})

My requirement is that if the array length became zero after the pull operator I need to remove the entire document for some reason.Is there a away to do this in a single query?

PS:I am using the mongodb driver.Not the mongoose

like image 716
M14 Avatar asked Jun 19 '17 11:06

M14


1 Answers

If I'm reading your question right, after the $pull, if the comments array is empty (zero length), then remove the document ({ _id: '', comments: [] }).

This should remove all documents where the comments array exists and is empty:

comments.remove({ comments: { $exists: true, $size: 0 } })

I had a similar requirement and used this (using mongoose though):

await Attributes.update({}, { $pull: { values: { id: { $in: valueIds } } } }, { multi: true })
await Attributes.remove({ values: { $exists: true, $size: 0 } })

Not sure if it's possible to do this in one operation or not.

like image 89
Stephen Last Avatar answered Nov 10 '22 00:11

Stephen Last