使用项目和过滤器进行Mongoose查询

时间:2017-02-27 15:49:43

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我有疑问:

 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中收到一个元素......

1 个答案:

答案 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
                ]
            }
        }
    }
])