在這里,我有來自多個表的多個欄位,這些值需要比較并需要顯示所需的結果。
SQL查詢:
select pd.service_id,ps.service_id from player pd, service ps where pd.subject_id=ps.subject_id and pd.service_id = ps.service_id
蒙哥查詢:
db.player.aggregate([
{
"$lookup":{
"from":"service",
"localField":"player.subject_id",
"foreignField":"subject_id",
"as":"ps"
}
},
{
"$unwind":"$ps"
},
{
"$match":{
"service_id":{
"$eq": "ps.service_id"
}
}
}
];
樣本輸入記錄:
玩家:
[{subject_id:23,service_id:1},{subject_id:76,service_id:9}]
服務:
[{subject_id:76,service_id:9},{subject_id:99,service_id:10}]
比賽打不開。我必須匹配兩個集合的 service_id。需要得到匹配的記錄。但無法看到任何結果。誰能幫我找出錯誤...
uj5u.com熱心網友回復:
在您的查詢中,如果要比較檔案本身的 2 個值,則需要使用$expr運算子
{
"$match":{
"$expr":{
"$eq": ["$service_id", "$ps.service_id"]
}
}
}
Mongo游樂場
替代解決方案:您需要使用不相關子查詢來“*加入”2個或更多條件
db.player.aggregate([
{
"$lookup": {
"from": "service",
"let": {
subject_id: "$subject_id",
service_id: "$service_id"
},
"pipeline": [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$$subject_id",
"$subject_id"
]
},
{
$eq: [
"$$service_id",
"$service_id"
]
}
]
}
}
}
],
"as": "ps"
}
},
// Remove non matched results
{
$match: {
"ps.0": {
$exists: true
}
}
},
// Remove temporal "ps" field
{
$addFields: {
"ps": "$$REMOVE"
}
}
])
Mongo游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/494465.html