MongoDB 4.4:清理双层嵌套数组无效对象并移除空数组
MongoDB 4.4 批量清理数组并移除空数组的更新方案
可以通过聚合管道式更新实现同一操作完成两个需求:过滤t数组中仅保留包含did、dst、den字段的对象,同时移除清理后为空的t数组及空的父级s字段。
执行命令
db.collection.updateMany( {}, // 可添加匹配条件定位目标文档 [ { $set: { "_a": { $map: { input: "$_a", as: "aItem", in: { $cond: [ { $ne: ["$$aItem._p", undefined] }, { "_p": { $mergeObjects: [ "$$aItem._p", { "s": { $let: { vars: { filteredA: { $filter: { input: "$$aItem._p.s.a.t", cond: { $and: [ { $ne: ["$$this.did", undefined] }, { $ne: ["$$this.dst", undefined] }, { $ne: ["$$this.den", undefined] } ]} } }, filteredC: { $filter: { input: "$$aItem._p.s.c.t", cond: { $and: [ { $ne: ["$$this.did", undefined] }, { $ne: ["$$this.dst", undefined] }, { $ne: ["$$this.den", undefined] } ]} } } }, in: { $cond: [ { $or: [{ $gt: [{ $size: "$$filteredA" }, 0] }, { $gt: [{ $size: "$$filteredC" }, 0] }] }, { $mergeObjects: [ "$$aItem._p.s", { "a": { $cond: [{ $gt: [{ $size: "$$filteredA" }, 0] }, { "t": "$$filteredA" }, "$$REMOVE"] }, "c": { $cond: [{ $gt: [{ $size: "$$filteredC" }, 0] }, { "t": "$$filteredC" }, "$$REMOVE"] } } ] }, "$$REMOVE" ] } } } } ] } }, "$$aItem" ] } } } } } ] )
逻辑说明
- 遍历
_a数组:用$map逐个处理_a内的元素,仅对包含_p字段的元素进行修改,其余元素保持原样。 - 过滤
t数组对象:通过$filter筛选t数组中同时存在did、dst、den字段的对象。 - 移除空数组及空父级:
- 若过滤后的
t数组长度为0,用$$REMOVE移除对应的a或c字段; - 若
s字段下的a和c都被移除(即s为空),则整体移除s字段;
- 若过滤后的
- 保留原始字段:用
$mergeObjects保留_p内的pid、h等无需修改的字段。
内容的提问来源于stack exchange,提问作者R2D2
相关产品推荐
相关产品推荐

