我被困在 MongoDB 查詢中。我有兩個系列。
計劃集合:
{
planName: 'TV1',
planFeatures: {
'AA1': true,
'AA2 : false',
'AA3': true,
'AA4': true,
'AA5': false
}
}, {
planName: 'TV2',
planFeatures: {
'AA1': true,
'AA2 : false',
'AA3': false,
'AA4': true,
'AA5': false
}
}, ..........
計劃特征集合
{
key: 'AA1',
label: 'ALPHA',
}, {
key: 'AA2',
label: 'BETA'
}, ..........
我正在嘗試聚合 2 個集合,以這樣一種方式,計劃集合中 planFeatures 欄位的鍵名稱應等于 planFeatures 集合的鍵欄位,例如(planFeatures 的鍵名)==(planFeatures.key)
AA1 == AA1
PaymentPlanFeatures.aggregate([
{
$lookup: {
from: 'plans',
let: { 'kkey': '$key'},
pipeline: [
{ $set: { 'planFeatures5': { '$objectToArray': '$planFeatures' }}},
{
$match: {
$expr: {
$eq: [
'$planFeatures5.k', '$$kkey'
]
}
}
}
],
as: 'paymentplans'
}
}
])
我希望我的結果看起來像這樣
[
{
"key": "AA1",
"label": "ALPHA",
"paymentplans": [
{
"planName": "TV1",
"planFeatures": {
"AA1": true,
"AA2": true,
"AA3": false
},
"__v": 0,
"planFeatures5": [
{
"k": "AA1",
"v": true
}
]
}
]
}, ..............
]
我在這個問題上停留了很長時間。有人可以幫我嗎?
uj5u.com熱心網友回復:
$planFeatures5.k回傳字串陣列,您應該在管道中使用$in運算子進行$match階段。$lookup
{
$in: [
"$$kkey",
"$planFeatures5.k"
]
}
db.planFeatures.aggregate([
{
$lookup: {
from: "plans",
let: {
"kkey": "$key"
},
pipeline: [
{
$set: {
"planFeatures5": {
"$objectToArray": "$planFeatures"
}
}
},
{
$match: {
$expr: {
$in: [
"$$kkey",
"$planFeatures5.k"
]
}
}
}
],
as: "paymentplans"
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/476763.html
