如何过滤 mongodb 中的 $lookup 结果

How to filter $lookup result in mongodb

我有两个合集:

users: [
    {
        name: 'John',
        children: ["Mary"]
    },
    {
        name: 'Mary',
        children: []
    }
]

tokens: [
    {
        name: "someToken",
        owner: "John"
    }
]

我想按令牌名称和 returns 用户按所有者和该用户的所有子项搜索。例如:

if (query value is 'someToken') then add to results John data from collection
if ('John' has childs) then add to results him children

我的尝试:

$project

$pipeline

这些 return 所有用户。不管查询值是什么,

您可以考虑从 token 开始聚合。按您的查询值执行 $match,然后执行 $lookup

db.tokens.aggregate([
  {
    $match: {
      name: "someTokenName"
    }
  },
  {
    "$lookup": {
      "from": "users",
      "localField": "owner",
      "foreignField": "name",
      "as": "usersLookup"
    }
  },
  {
    $project: {
      name: "$owner",
      children: {
        "$reduce": {
          "input": "$usersLookup.children",
          "initialValue": [],
          "in": {
            "$concatArrays": [
              "$$value",
              "$$this"
            ]
          }
        }
      }
    }
  }
])

这里是Mongo playground供您参考。