MongoDB - Use $where inside $elemMatch

Viewed 1817

Let's say I have a collection with accounts that each account has array of users:

{
  _id: 1,
  users: [
    {
      firstName: a,
      lastName: b
    },
    {
      firstName: c,
      lastName: c
    }
  ]
}

I want to query all accounts where at least one user has the same firstName and lastName

I tried to do something like this:

db.accounts.find({users: {
    $elemMatch: {
        $where: "this.firstName == this.lastName"
    }
}})

But of course it didn't work because of this error:

Can't canonicalize query: BadValue $elemMatch cannot contain $where expression

I want to use the find and not aggregate. Is there some other way to do it?

3 Answers
Related