【问题标题】:Retrieve only the data positioned in the Index value of array in Mongodb仅检索位于MongoDB中数组索引值中的数据
【发布时间】:2016-12-02 20:47:49
【问题描述】:

我陷入了查询场景。 我在 Mongodb 中有一个 json 结构,在其中我必须根据元素“索引”查询文档。

{"List" : {
"List1" : [11,12,13,14,15,16],
"List2" : [11,11,11,11,11,11]
},
"Values" : ["APPLE", "ORANGE", "BANANA", "MANGO", "PAPAYA", "KIWI"],
"Index" : [1,2,3,1,2,3]
}

过滤器应该基于“索引”,它是“1”,我想显示如下。

{"List" : {
"List1" : [11,14],
"List2" : [11,11]
},
"Values" : ["APPLE","MANGO"],
"Index" : [1,1]
}

下面是我执行的查询

db.getCollection('TEST').find({"Index": 3} ,
{  "Values": 1,"List":1,"Index": 1, "Index.$": 1}
)

因为我给出了位置参数(“Index.$”:1),所以我得到了除了索引值中的所有数据之外的所有数据

【问题讨论】:

标签: mongodb mongodb-query


【解决方案1】:

使用当前 Mongo 3.4 版本,您可以 $zip 结合 $range 生成数组索引和字段,$filter 匹配索引字段和 $addFields 添加到原始字段。

最后一步是$map根据与$arrayElemAt的匹配索引来$map >

aggregate([{
    $addFields: {
        match: {
            $filter: {
                input: {
                    $zip: {
                        inputs: ["$Index", {
                            $range: [0, {
                                $size: "$Index"
                            }]
                        }]
                    }
                },
                as: "val",
                cond: {
                    $eq: [{
                        $arrayElemAt: ["$$val", 0]
                    }, 1]
                }
            }
        }
    }
}, {
    $project: {
        "List": {
            "List1": {
                $map: {
                    input: "$match",
                    as: "index",
                    in: {
                        $arrayElemAt: ["$List.List1", {
                            $arrayElemAt: ["$$index", -1]
                        }]
                    }
                }
            },
            "List2": {
                $map: {
                    input: "$match",
                    as: "index",
                    in: {
                        $arrayElemAt: ["$List.List2", {
                            $arrayElemAt: ["$$index", -1]
                        }]
                    }
                }
            }
        },
        "Values": {
            $map: {
                input: "$match",
                as: "index",
                in: {
                    $arrayElemAt: ["$Values", {
                        $arrayElemAt: ["$$index", -1]
                    }]
                }
            }
        },
        "Index": {
            $map: {
                input: "$match",
                as: "index",
                in: {
                    $arrayElemAt: ["$Index", {
                        $arrayElemAt: ["$$index", -1]
                    }]
                }
            }
        },
        _id: 0
    }
}]).pretty();

【讨论】:

    猜你喜欢
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多