Mongodb deletes document if array is zero after $ pull in one request

I have a requirement where my schematic comments

looks like this

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

      

I would like to pull elements based on a field userId

. I am making the following request

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

      

My requirement is that if the length of the array went to zero after the pull statement, then I need to delete the entire document for some reason. Is it possible to do this in one request?

PS: I am using mongodb driver. Not the mongoose

+3


source to share


2 answers


You can use middlewares for this.

http://mongoosejs.com/docs/middleware.html



Write a pre / post update method in mongodb to check your status.

+1


source


If I read your question correctly, after $pull

if the array is comments

empty (zero length), delete the document ( { _id: '', comments: [] }

).

This should remove all documents where the array exists comments

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 is possible to do this in one operation or not.

+1


source







All Articles