从嵌套数组中筛选另一嵌套数组不存在的元素
MongoDB嵌套数组元素对比与操作方案
任务1:筛选_a[]._d[].pid中不存在于_a[]._p[]的项
示例文档
{ "_id": 123, "_a": [ { "aid": 10, "_p": [ { "pid": 1, "x": "C" }, { "pid": 2, "x": "B" }, { "pid": 4, "x": "A" } ], "_d": [ { "pid": 2, "x": "M" }, { "pid": 5, "x": "M" }, { "pid": 7, "x": "M" } ] } ] }
预期输出
{ "aid": 10, "pid": 5 } { "aid": 10, "pid": 7 }
聚合查询语句
db.collection.aggregate([ { $unwind: "$_a" }, { $project: { _id: 0, aid: "$_a.aid", unmatchedPids: { $filter: { input: "$_a._d", cond: { $not: { $in: ["$$this.pid", "$_a._p.pid"] } } } } } }, { $unwind: "$unmatchedPids" }, { $project: { aid: 1, pid: "$unmatchedPids.pid" } } ])
执行逻辑
$unwind拆分_a数组,将每个子文档独立处理$project阶段用$filter筛选出_d中pid不在_p.pid集合内的元素- 再次
$unwind拆分筛选后的结果数组,将每个匹配项单独输出 - 最后
$project只保留需要的aid和pid字段
任务2:移除_a[]._d[]中pid不存在于_a[]._p[]的对象
更新操作语句
db.collection.updateMany( {}, [ { $set: { "_a": { $map: { input: "$_a", as: "item", in: { aid: "$$item.aid", _p: "$$item._p", _d: { $filter: { input: "$$item._d", cond: { $in: ["$$this.pid", "$$item._p.pid"] } } } } } } } } ] )
执行逻辑
- 使用聚合管道模式执行批量更新,遍历
_a数组的每个子文档 - 对每个子文档,用
$filter保留_d中pid存在于_p.pid集合内的对象 - 重新组装
_a数组并替换原字段,完成文档更新
内容的提问来源于stack exchange,提问作者R2D2
相关产品推荐
相关产品推荐

