basickarl
basickarl

Reputation: 40444

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?

Upvotes: 2

Views: 7759

Answers (1)

Sede
Sede

Reputation: 61225

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 ] }

Upvotes: 7

Related Questions