Accessing element of object array by index in one project step?

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"
        }
    }
);

I can’t figure out how to edit my post. The first sentence is supposed to say “I’m using mongo 4.2”.

Hello : )

We cant do that,paths cannot have array indexes.But we can use temp variables to get the
index,and continue the path with the variable.

For example for your project this would work

{
      "$project": {
        "baz": {
          "$let": {
            "vars": {
              "firstMember": {
                "$arrayElemAt": [
                  "$foo",
                  0
                ]
              }
            },
            "in": "$$firstMember.bar.baz"
          }
        }
      }
    }

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.