【问题标题】:How do you access a specific array item in MongoDB projection aggregation?如何访问 MongoDB 投影聚合中的特定数组项?
【发布时间】:2015-09-08 22:54:21
【问题描述】:

我正在尝试在 MongoDB 聚合函数中创建投影,请参阅以下内容:

[
    {$match : {"geo" : {$ne: null}}},
    {$project : {"id" : "$id_str", lat: "$geo.coordinates.0", lon: "$geo.coordinates.1"}}
]

但是,当我这样做时,它不会传递数组项,它只是将一个空数组投影到属性 lat 和 lon。

这里需要什么?我查看了文档但无法弄清楚,甚至尝试了 $unwind 和 $group 的排列但没有成功。

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    帮助您实现这一目标的功能尚不可用。但是,将有一个新的聚合运算符为给定索引提供数组元素。新表达式称为 $arrayElemAt

    使用可用于 MongoDB 版本 3.2.X 及更高版本的新聚合运算符,这将返回给定索引的数组元素。新表达式称为$arrayElemAt。它接受两个参数,一个数组和一个索引,并返回数组中给定索引处的元素。负索引被接受为数组后面的索引。如果索引超出范围,则返回缺失值,这意味着该字段将不存在于输出中:

    var pipeline = [    
        { $match : {"geo" : {$ne: null}}},
        {
            $project: {
                _id: "$id_str", 
                lat: { $arrayElemAt: ['$geo.coordinates', 0] },
                lon: { $arrayElemAt: ['$geo.coordinates', 1] }
            }
        }
    ];
    

    作为目前的解决方法(假设坐标数组在任何给定时间总是有两个元素),您可以尝试以下聚合管道,该管道将利用 $first 和 $last 将累加器运算符分组以获取$sort 之后的元素:

    var pipeline = [
        {$match : {"geo" : {$ne: null}}},
        { "$unwind": "$geo.coordinates" },
        { "$sort": {"geo.coordinates": 1} } ,
        {
            "$group": {
                "_id": "$_id",
                "lat": { "$first": "$geo.coordinates" },
                "lon": { "$last": "$geo.coordinates" }
            }
        }
    ];
    

    【讨论】:

      【解决方案2】:

      您可以在管道的项目阶段简单地使用它:-

      { $项目:{ _id:'$_id', 纬度:{$arrayElemAt:['$geo.coordinates',0]}, lon: {$arrayElemAt : ['$geo.coordinates',1]}, } }

      如果您想更详细地了解 arrayElemAt 聚合运算符,请单击以下链接:-

      https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/

      更多信息:-

      “所有文档必须以相同的顺序存储位置数据。如果您使用纬度和经度作为坐标系,请始终先存储经度。MongoDB 的 2d 球形索引运算符仅识别 [经度,纬度] 排序。”

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-04
        • 2021-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多