【问题标题】:Mongoose query with project and filter带有项目和过滤器的猫鼬查询
【发布时间】:2017-07-18 07:36:02
【问题描述】:

我有疑问:

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

【问题讨论】:

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


    【解决方案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
                    ]
                }
            }
        }
    ])
    

    【讨论】:

      猜你喜欢
      • 2018-03-19
      • 2016-04-21
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-09
      • 2013-05-06
      相关资源
      最近更新 更多