我有两个集合user和transaction,事务有两个字段customer和seller,用户有两个字段name和email,用户集合包含客户和卖家的数据。
我想要输出,就好像email传递给customer,那么seller细节应该来自查找,如果email传递给seller,那么customer细节应该来自查找。
我所做的是,动态地传递值email,email值可以属于customer或seller,如果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,快递和猫鼬。
发布于 2020-09-23 14:05:08
localField只允许字符串,可以使用用管道查找,
letpipeline将匹配条件与查找集合的字段放在一起{
$lookup: {
from: "user",
let: {
localField: {
$cond: [{
if: { $eq: ["$customer", email] },
then: "$seller",
else: "$customer",
}]
}
},
pipeline: [
{ $match: { $expr: { $eq: ["$email", "$$localField"] } } }
],
as: "user"
}
}https://stackoverflow.com/questions/64029365
复制相似问题