如果在单个查询中 $pull 后数组计数为零,则 mongodb 删除文档 [英] mongodb remove document if array count zero after $pull in a single query
问题描述
我有一个要求,其中我的 comments
架构如下所示
I have a requirement where my comments
schema looks like the following
{
"_id": 1,
"comments": [
{ "userId": "123", "comment": "nice" },
{ "userId": "124", "comment": "super"}
]
}
我想根据 userId
字段提取元素.我正在做以下查询
I would like to pull the elements based on the userId
field.
I am doing the following query
comments.update({},{$pull:{comments:{userId:"123"}}})
我的要求是,如果在 pull 运算符之后数组长度变为零,我需要出于某种原因删除整个文档.是否可以在单个查询中执行此操作?
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:我使用的是 mongodb 驱动程序.不是猫鼬
PS:I am using the mongodb driver.Not the mongoose
推荐答案
如果我没看错你的问题,在 $pull
之后,如果 comments
数组是空(零长度),然后删除文档({ _id: '', comments: [] }
).
If I'm reading your question right, after the $pull
, if the comments
array is empty (zero length), then remove the document ({ _id: '', comments: [] }
).
这应该删除 comments
数组存在且为空的所有文档:
This should remove all documents where the comments
array exists and is empty:
comments.remove({ comments: { $exists: true, $size: 0 } })
我有一个类似的要求并使用了这个(虽然使用了mongoose
):
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.
这篇关于如果在单个查询中 $pull 后数组计数为零,则 mongodb 删除文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!