【问题标题】:how to use a variable defined in let as property name of an object field in the pipeline in a lookup?如何在查找中使用 let 中定义的变量作为管道中对象字段的属性名称?
【发布时间】:2023-01-09 16:29:41
【问题描述】:
user schema:

{
  _id: "OjectId",
}
interaction schema:

{
  blocked: {
   // properties with names from user._id and value of true
  }
}
                db.user.aggregate([{
                  $lookup: {
                    from: "interaction",
                    as: "remove",
                    let: { tar_id: "$_id" },
                    pipeline: [
                      {
                        $match: {
                          [`blocked[$$tar_id]`]: true,
                        },
                      },
                      {
                        $limit: 1,
                      },
                      {
                        $project: {
                          _id: 0,
                          remove: "true",
                        },
                      },
                    ],
                  },
                }]}

注意这一行:

  [`blocked[$$tar_id]`]: true,

以上查找是否有效?如果没有,我怎样才能让它按预期工作?

编辑:

测试。这是行不通的。问题仍然存在,我如何才能按预期工作?

【问题讨论】:

  • 请提供两个集合的样本文件
  • @nimrodserok 添加

标签: mongodb objectid mongodb-indexes object-identity


【解决方案1】:

一种选择是:

db.user.aggregate([
  {
    $lookup: {
      from: "interaction",
      as: "remove",
      let: {
        tar_id: {
          $toString: "$_id"
        }
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $gt: [
                {
                  $size: {
                    $filter: {
                      input: {
                        $objectToArray: "$blocked"
                      },
                      cond: {
                        $eq: [
                          "$$tar_id",
                          "$$this.k"
                        ]
                      }
                    }
                  }
                },
                0
              ]
            }
          }
        },
        {
          $limit: 1
        },
        {
          $project: {
            _id: 0,
            remove: "true"
          }
        }
      ]
    }
  }
])

查看它在playground example 上的工作原理

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    相关资源
    最近更新 更多