Represent object present at a position inside an array in mongoDB aggregation

倾然丶 夕夏残阳落幕 提交于 2019-12-07 04:15:25

You can combine the project stages and use $let to project the index.

$project: {
    indexes: {
        $let: {
            vars: {
                obj: {
                    $arrayElemAt: [{
                        "$cond": {
                            "if": {
                                "$eq": ["$coupon_type", 1]
                            },
                            "then": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr"],
                            "else": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr", "$coupon_codes", {
                                indexes: conditions
                            }]
                        }
                    }, 7]
                }
            },
            in: "$$obj.indexes"
        }
    }
}

you can achieve this by adding a second $project stage:

    db.collection.aggregate([{
            "$project": {
                "result": {
                    "$cond": {
                        "if": {
                            "$eq": ["$coupon_type", 1]
                        },
                        "then": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr"],
                        "else": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr", "$coupon_codes", {
                            indexes: conditions
                        }]
                    }
                }
            }
        },
        {
            "$project": {
                obj: { $arrayElemAt: [ "$result", 7 ] } 

        }, 
        {"$project": {
                obj: "$obj.indexes" }
        } 
])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!