MrNantir
MrNantir

Reputation: 85

Using $elemMatch with value from document

I'm having some issues where I try to use elemMatch in an aggregation pipeline.

I have this document (I've removed all unecessary noise)

{
  "_id": { "$binary": "UUVDF2zrr0GPoab2ANKyHA==", "$type": "03" },
  "Roles": {
    "_id": { "$binary": "k9b3LmRO7USO6YljYSnrCA==", "$type": "03" },
    "IsMandatory": true
  },
  "Employees": {
    "_id": { "$binary": "ycVu1XzEcEyQDKb/AMHo6g==", "$type": "03" },
    "RoleContexts": [
      {
        "TraineeRoleId": { "$binary": "k9b3LmRO7USO6YljYSnrCA==", "$type": "03"},
      }
    ]
  }
}

And I would like to remove non-matches from the result by using this $match pipeline:

{
    $and: [
        { "Roles.IsMandatory": true },
        { 
            "Employees.RoleContexts": {
                $elemMatch: {
                    "TraineeRoleId": "$Roles._id"
                }                
            }
        }
    ]
}

The expected result would be the that the aforementioned document is matched.

However I get no results, it seems that the $Roles._id is not working. When I hardcode then _id value it works.

I've looked at the documentation, but I can't figure out what I'm doing wrong.

Upvotes: 0

Views: 55

Answers (1)

turivishal
turivishal

Reputation: 36144

  • $expr can build query expressions that compare fields from the same document in a match condition.
{
  $and: [
    {
      "Roles.IsMandatory": true
    },
    {
      $expr: {
        $in: [
          "$Roles._id",
          "$Employees.RoleContexts.TraineeRoleId"
        ]
      }
    }
  ]
}

Playground

Upvotes: 1

Related Questions