I’m using mongo I have a collection c
with a document that looks like this:
{
"foo": [
{
"bar": {
"baz": "qux"
}
}
]
}
All I need from foo
is bar.baz
in the first element of foo
. I don’t know why the documents were created like this, and if I were designing the document schema I wouldn’t do this, but I don’t have control over the data source.
I can do this with two steps of a project:
db.c.aggregate(
{
$project: {
foo_zero: {
$arrayElemAt: ["$foo", 0]
}
}
},
{
$project: {
_id: 0,
baz: "$foo_zero.bar.baz"
}
}
);
but this seems overly complicated.
Can I do this one with one project instead of two?
Something like this would be much nicer:
db.c.aggregate(
{
$project: {
baz: "$foo.0.bar.baz"
}
}
);