2

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?

1 Answer 1

7

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 ] }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.