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