MongoDB使用$pull删除嵌套数组指定元素不生效如何解决
问题原因
你的更新操作语法不符合MongoDB的$pull操作符要求:
$pull的参数结构必须是 { <字段路径>: <移除匹配条件> },不支持在$pull下直接嵌套$or操作符,这是你返回执行失败的核心原因。- 原写法未添加全数组匹配标识符,只能匹配calendar数组的第一个元素,无法批量处理所有数组元素;且仅能固定匹配
calendar.days.1、calendar.days.2两个路径,扩展性差。
解决方案
通用方案(适配MongoDB 3.6及以上版本,推荐)
使用数组筛选器动态匹配calendar数组下所有days对象中包含目标词汇的数组,批量移除:
var words = ['test'] Calendar.update( // 查询条件:任意calendar元素的任意days属性值数组包含目标词汇 { "calendar": { $elemMatch: { $expr: { $gt: [ { $size: { $filter: { input: { $objectToArray: "$days" }, cond: { $gt: [ { $size: { $setIntersection: [ "$$this.v", words ] } }, 0 ] } } } }, 0 ] } } }, // 更新操作 { $pull: { "calendar.$[elem].days.$[day].v": { $in: words } } }, { multi: true, arrayFilters: [ { "elem": { $exists: true } }, { "day.v": { $elemMatch: { $in: words } } } ] } )
固定天数场景简易写法
如果天数范围固定(比如最多31天),可以直接枚举所有天数路径,写法更简洁:
var words = ['test'] Calendar.update( {$or: [ {"calendar.days.1": {$in: words}}, {"calendar.days.2": {$in: words}}, {"calendar.days.3": {$in: words}} // 按需补充其他天数的匹配规则 ]}, { $pull: { "calendar.$[].days.1": {$in: words}, "calendar.$[].days.2": {$in: words}, "calendar.$[].days.3": {$in: words} // 对应补充其他天数的移除规则,$[]表示匹配calendar数组所有元素 } }, {multi: true} )
内容的提问来源于stack exchange,提问作者Taner Tunçer
相关产品推荐
相关产品推荐

