【问题标题】:Applying condition on localfield in aggregate in mongodb在 mongodb 中对 localfield 应用条件聚合
【发布时间】:2021-01-09 17:42:49
【问题描述】:

我有两个集合usertransaction,交易有两个字段customerseller,用户有两个字段nameemail.,用户集合包含客户和卖家的数据

我希望输出好像传递的email 属于customer 然后seller 详细信息应该来自查找,如果传递的email 属于seller 那么customer 详细信息应该来自查找

我所做的是,我正在动态传递值emailemail 值可以属于customerseller,如果email 匹配seller,那么我想要localfield查找为customer,反之亦然。以下是我尝试过的。

const email = req.email;

transaction.aggregate([{
    $match: {
      $or: [{
          customer: email,
        },
        {
          seller: email,
        },
      ],
    },
  },
  {
    $lookup: {
      from: "user",
      localField: {
        $cond: [{
          if: {
            $eq: ["$customer", email]
          },
          then: "seller",
          else: "customer",
        }],
      },
      foreignField: "email",
      as: "user",
    },
  },
  {
    $unwind: "$user"
  },
]);

但是对于上面的查询错误如下

$lookup argument 'localField' must be a string

我正在使用 nodejs、express 和 mongoose。

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    localField 只允许字符串,你可以使用lookup with pipeline

    • let 定义您的条件逻辑
    • pipeline 将您的匹配条件放入查找集合的字段
    {
        $lookup: {
            from: "user",
            let: {
                localField: {
                    $cond: [{
                        if: { $eq: ["$customer", email] },
                        then: "$seller",
                        else: "$customer",
                    }]
                }
            },
            pipeline: [
                { $match: { $expr: { $eq: ["$email", "$$localField"] } } }
            ],
            as: "user"
        }
    }
    

    【讨论】:

    • $cond 在这种情况下,值应该只是数组中的一个对象
    • @SemyonVyskubov 没有准确地了解您。
    猜你喜欢
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2021-02-22
    • 2019-03-05
    • 2023-03-16
    相关资源
    最近更新 更多