我有疑问:
Model.aggregate([{
$lookup: {
from: 'translations',
localField: '_id',
foreignField: 'item_id',
as: 'translation'
},
}, {
$project: {
"label": "$label",
"items": "$items",
"translation": {
"$filter": {
"input": "$translation",
"as": "page",
"cond": {
"$eq": ["$$page.lang_key", lang]
}
}
}
}
}])
结果:
[ { _id: 58b2ca5b9ac42bac7aaed48a,
label: 'Main',
items: [ [Object] ],
translation: [ [Object] ] } ]
如何使字段translation
不是数组?
因为我总是只在Array中收到一个元素......
答案 0 :(得分:1)
由于您只在阵列中收到一个元素,因此您可以使用 $unwind
或 $arrayElemAt
来展平数组并生成子文档。对于后者,以下内容适用于您:
Model.aggregate([
{
"$lookup": {
"from": "translations",
"localField": "_id",
"foreignField": "item_id",
"as": "translation"
}
},
{
"$project": {
"label": 1, "items": 1,
"translation": {
"$arrayElemAt": [
{
"$filter": {
"input": "$translation",
"as": "page",
"cond": { "$eq": ["$$page.lang_key", lang] }
}
},
0
]
}
}
}
])