MongoDB Aggregate-匹配集合A上存在但集合B上不存在的文档

yzckvree  于 2022-10-22  发布在  Go
关注(0)|答案(1)|浏览(172)

如何使用MongoDB聚合匹配集合A上存在但集合B上不存在的文档?
收藏A:

[{
    "_id": 1,
    "operation":"SEC",
    "name":"x"
},{
    "_id": 2,
    "operation": "SEC",
    "name": "y"
},
{
    "_id": 3,
    "operation": "SEC",
    "name": "z"
}]

收藏集B:

[
    {
        "_id": 1,
        "operation": "SEC",
        "name": "x"
    },
    {
        "_id": 2,
        "operation": "SEC",
        "name": "y"
    }
]

预期产出:

[
    {
        "_id": 3,
        "operation": "SEC",
        "name": "z"
    }
]
jdzmm42g

jdzmm42g1#

一种选择是使用具有$$ROOT$match不匹配文档的$lookup管道:

db.CollectionA.aggregate([
  {$lookup: {
      from: "CollectionB",
      let: {root: "$$ROOT"},
      pipeline: [{$match: {$expr: {$eq: ["$$ROOT", "$$root"]}}}],
      as: "collectionB"
  }},
  {$match: {"collectionB.0": {$exists: false}}},
  {$unset: "collectionB"}
])

了解它在playground example上的工作原理

相关问题