Search code examples
databasemongodbmongoosepipelineaggregation

Referencing another field of subdocument in `$elemMatch`


I'm trying to perform an $elemMatch in a $match aggregation stage where I want to find if there is a document in an array (commitments) of subdocuments whose property tracksThisWeek is smaller than its frequency property, but I'm not sure how can I reference another field of the subdocument in question, I came up with:

{
    $match: {
        commitments: {
            $elemMatch: {
                tracksThisWeek: {
                    $lt: '$frequency',
                },
            },
        },
    },
},

I have a document in the collection that should be returned from this aggregation but isn't, any help is appreciated :)


Solution

  • This can't be done, you can't reference any fields in the query language, What you can do is use $expr with aggregation operators, like this:

    db.collection.aggregate([
      {
        $match: {
          $expr: {
            $gt: [
              {
                $size: {
                  $filter: {
                    input: "$commitments",
                    cond: {
                      $lt: [
                        "$$this.tracksThisWeek",
                        "$$this.frequency"
                      ]
                    }
                  }
                }
              },
              0
            ]
          }
        }
      }
    ])
    

    Mongo Playground