Search code examples
mongodbmongodb-queryaggregation-frameworkmongoskin

Get specific field in array mongodb and return as array


I have the following document:

{
    array: [
        {
            type: 'error',
            data: 1
        },
        {
            type: 'error',
            data: 2
        }
    ]
}

Is there anyway for my to get only the data field in each array element and return it as an array? Like the following:

[1, 2] // <--- array containing only the data fields

The mongodb projection documentation doesn't seem to cover this?


Solution

  • You can use aggregation and the $map operator.

    db.collection.aggregate([
        { 
            "$project": { "_id": 0, "data": { 
                "$map": { "input": "$array", "as": "ar", "in": "$$ar.data" } } }
        }
    ])
    

    Which yields:

    { "data" : [ 1, 2 ] }