如何在MongoDB投影聚合中访问特定的数组项? [英] How do you access a specific array item in MongoDB projection aggregation?

查看:101
本文介绍了如何在MongoDB投影聚合中访问特定的数组项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a projection within a MongoDB aggregation function, see the following:

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

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

However when I do this it does not pass over the array item it simply projects an empty array to the properties lat and lon.

这里需要什么?我看过文档,但无法弄清楚,甚至尝试对$ unwind和$ group进行排列,但没有成功.

What is needed here? I have looked at the Documentation but cannot figure it out, and even tried a permutation of $unwind and $group but with no success.

推荐答案

该功能尚不可用.但是,将有一个新的聚合运算符,该运算符为给定索引提供数组元素.新表达式称为 $arrayElemAt

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

Use the new aggregation operator that's available for MongoDB versions 3.2.X and greater, this returns an array element for a given index. The new expression is called $arrayElemAt. It takes two arguments, an array and an index and returns the element at the given index in the array. Negative indices are accepted as indexes from the back of the array. If the index is out of bounds, it returns the missing value, meaning the field will not exist in the output:

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

作为目前的一种解决方法(假设坐标数组在任何给定时间始终包含两个元素),您可以尝试以下聚合管道,该管道将利用

As a workaround for now (assuming the coordinates array will always have two elements at any given time), you could try the following aggregation pipeline which will take advantage of the $first and $last group accumulator operators to get the elements after a $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" }
        }
    }
];

这篇关于如何在MongoDB投影聚合中访问特定的数组项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆