How to access a specific element of an array in MongoDB prediction aggregation?

I am trying to create a projection in MongoDB aggregation function, see the following:

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

      

However, when I do this, it doesn't go over the array element, it just projects an empty array onto the lat and lon properties.

What is needed here? I've looked at the documentation but can't figure it out, and even tried swapping $ unwind and $ group but no success.

+3


source to share


1 answer


A feature to help you achieve this is not yet available. However, there will be a new aggregation operator that gives the array element for the given index. The new expression is called $arrayElemAt

Use the new aggregation operator available for MongoDB versions 3.2.X

and above, this returns the array element for the given index. The new expression is called . It takes two arguments, an array and an index, and returns the element at the specified index in the array. Negative indices are accepted as indices on the back of the array. If the index is out of bounds, it returns the missing value, that is, the field will not be present in the output: $arrayElemAt

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

      



As a workaround right now (assuming that the coordinates will always be an array of two elements at any time), you can try the following pipeline aggregation, which will take advantage of and operators battery groups to get the items after : $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" }
        }
    }
];

      

+3


source







All Articles