我有兩個集合,我正在對其執行查找以獲取組合資料。
公司 :
{
"_id": "638760ea-d109-49fd-8447-b52fe39227a3",
"company": "test",
"phones": [
{
"iso": "in",
"number": "54666",
"label": "CF_61a8c36b3368b0b21dbfbe3d"
},
{
"iso": "hu",
"number": "54433",
"label": "CF_61a8c37d3368b0b21dbfbe3e"
}
]
}
聯系人標簽:
{
"_id": "096b0446-1099-49f4-87fc-21e583581780",
"values": [
{
"id": "0a5c3f36-a06d-4f34-a1a9-9bbef7370940",
"code": "CF_61a8c36b3368b0b21dbfbe3d",
"value": "Personal"
},
{
"id": "693574f9-cb30-48b1-9394-7673c9e71f33",
"code": "CF_61a8c37d3368b0b21dbfbe3e",
"value": "Home"
}
]
}
我想要輸出為
{
"_id": "638760ea-d109-49fd-8447-b52fe39227a3",
"company": "test",
"phones": [
{
"iso": "in",
"number": "54666",
"label": "CF_61a8c36b3368b0b21dbfbe3d",
"value": "Personal"
},
{
"iso": "hu",
"number": "54433",
"label": "CF_61a8c37d3368b0b21dbfbe3e",
"value": "Home"
}
]
}
這是我申請獲取結果的查找
{
from: 'ContactLables',
let:'ContactLablesCode':'$values.code',
pipeline: [
{ "$match": {
"$expr": { "$eq": [ "$phones.label", "$$ContactLablesCode" ] }
}}
],
as: 'phoneLables'
}
上面的查詢沒有給我任何結果,對此有什么建議嗎?
uj5u.com熱心網友回復:
查詢1
- 放松手機
- 使用管道查找但版本 MongoDB 5 我們有 localfield/foreighfield 管道
localfield= the phones.label和foreign=array with the codes- 如果 match => 陣列有我們想要的標簽,但我們不知道哪個成員
- 展開并匹配以僅保留我們
phone.label的例如“Home”的值 - 現在從每部手機中,我們都可以從其他系列中獲得價值
- 使用設定/取消設定修復結構(1 組并且
"$$REMOVE"也可以使用) - 終于團回來,把手機推給
_id主人
*為了讓它更快,你需要多鍵索引ContactLables.value和 MongoDB 5(這里的查詢是為了讓 MongoDB 5 更快并且使用 idenx)
測驗代碼在這里
Company.aggregate(
[{"$unwind":"$phones"},
{"$lookup":
{"from":"ContactLables",
"localField":"phones.label",
"foreignField":"values.code",
"pipeline":
[{"$unwind":"$values"},
{"$match":{"$expr":{"$eq":["$values.code", "$$label"]}}},
{"$project":{"_id":0, "value":"$values.value"}}],
"as":"results",
"let":{"label":"$phones.label"}}},
{"$set":{"phones.value":{"$first":"$results.value"}}},
{"$unset":["results"]},
{"$group":
{"_id":"$_id",
"company":{"$first":"$company"},
"phones":{"$push":"$phones"}}}])
查詢2
- 與上面相同,但在管道內部使用 reduce 而不是 unwind 和 match
- reduce 以查找匹配的成員,并保留其值,例如“Home”
測驗代碼在這里
Company.aggregate(
[{"$unwind":"$phones"},
{"$lookup":
{"from":"ContactLables",
"localField":"phones.label",
"foreignField":"values.code",
"pipeline":
[{"$project":
{"_id":0,
"value":
{"$reduce":
{"input":"$values",
"initialValue":null,
"in":
{"$let":
{"vars":{"v":"$$value"},
"in":
{"$cond":
[{"$eq":["$$this.code", "$$label"]}, "$$this.value",
"$$v"]}}}}}}}],
"as":"results",
"let":{"label":"$phones.label"}}},
{"$set":{"phones.value":{"$first":"$results.value"}}},
{"$unset":["results"]},
{"$group":
{"_id":"$_id",
"company":{"$first":"$company"},
"phones":{"$push":"$phones"}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/419761.html
標籤:
