表示在mongoDB聚合中出现在数组内部位置的对象

时间:2017-01-16 12:08:10

标签: mongodb mongodb-query aggregation-framework

在聚合中,我正在尝试投射object(which is an array) position 7 inside an array。例如,我有以下字段

{
        "$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 ] } // here how to project indexes.

    }

现在coupon_type: 0我将把结果投影为["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr", "$coupon_codes", { indexes: conditions}]

现在,我希望在下一个管道中投射的字段是'索引'所以我试着写$arrayElemAt: [ "$result", 7 ]给我第7个索引元素,这是正确的,但我应该如何表示对象'索引'出席第7位。

总之,我想写一些像$arrayElemAt: [ "$result", 7 ].indexes这样的东西,这不是指向卑鄙的正确方法。

任何人都可以告诉我我该怎么做。

2 个答案:

答案 0 :(得分:1)

您可以通过添加第二个$ project阶段来实现这一目标:

    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" }
        } 
])

答案 1 :(得分:1)

您可以组合项目阶段并使用$let来投影索引。

$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"
        }
    }
}