我有一个用例,我需要连接 MongoDB 中的两个集合,但只有满足两个条件之一时才必须进行连接。 下面给出了 SQL 等效查询。我如何在 MongoDB 中翻译它?
SELECT *
FROM MainTble i
Left JOIN SecondTable p
ON CASE
WHEN i.myPropert="SMS" and i.phoneNumber = p.phoneNumber THEN 1
WHEN i.myProperty="Email" and i.email = p.email THEN 1
ELSE 0
END = 1
您可以使用 $lookup 来实现类似的行为。在子管道中,使用
$addFields
创建辅助字段,然后在辅助字段上使用 $match
来过滤 $lookup
/ 连接结果。
db.mainTable.aggregate([
{
"$lookup": {
"from": "secondTable",
"let": {
"mainProperty": "$myProperty",
"mainPhoneNumber": "$phoneNumber",
"mainEmail": "$email"
},
"pipeline": [
{
"$addFields": {
"matched": {
$cond: [
{
$or: [
{
$and: [
{
$eq: [
"$$mainProperty",
"SMS"
]
},
{
$eq: [
"$$mainPhoneNumber",
"$phoneNumber"
]
}
]
},
{
$and: [
{
$eq: [
"$$mainProperty",
"Email"
]
},
{
$eq: [
"$$mainEmail",
"$email"
]
}
]
}
]
},
1,
0
]
}
}
},
{
$match: {
matched: 1
}
}
],
"as": "secondTableLookup"
}
}
])
这里是Mongo Playground供您参考。