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

廉价感情. 提交于 2021-02-08 12:57:16

问题


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


回答1:


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.




回答2:


You can use middlewares for this.

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

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



来源:https://stackoverflow.com/questions/44629010/mongodb-remove-document-if-array-count-zero-after-pull-in-a-single-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!