首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >mongodb中集料地的应用条件

mongodb中集料地的应用条件
EN

Stack Overflow用户
提问于 2020-09-23 13:43:32
回答 1查看 528关注 0票数 1

我有两个集合usertransaction,事务有两个字段customerseller,用户有两个字段nameemail,用户集合包含客户和卖家的数据。

我想要输出,就好像email传递给customer,那么seller细节应该来自查找,如果email传递给seller,那么customer细节应该来自查找。

我所做的是,动态地传递值emailemail值可以属于customerseller,如果email匹配seller,则希望查找localfield作为customer,反之亦然。以下是我尝试过的。

代码语言:javascript
复制
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"
  },
]);

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

代码语言:javascript
复制
$lookup argument 'localField' must be a string

我用的是nodejs,快递和猫鼬。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-23 14:05:08

localField只允许字符串,可以使用用管道查找

  • 定义条件逻辑的let
  • pipeline将匹配条件与查找集合的字段放在一起
代码语言:javascript
复制
{
    $lookup: {
        from: "user",
        let: {
            localField: {
                $cond: [{
                    if: { $eq: ["$customer", email] },
                    then: "$seller",
                    else: "$customer",
                }]
            }
        },
        pipeline: [
            { $match: { $expr: { $eq: ["$email", "$$localField"] } } }
        ],
        as: "user"
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64029365

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档