How to compare two fields of the same document for equality in MongoDB?

advertisements

I have a MongoDB collection of documents with the following "schema" :

{
  field1: value1,
  field2: value2
}

I want to run a query with "$match" in a pipeline to check the equality of field1 and field2 values.

Something like "field1" == "field2".

How can I do this?

Thank you people!


db.c.aggregate([{
    $project : {
        equal : {
            $eq : ["$field1", "$field2"]  // to judge like your :  "valueof(field1) == valueof(field2)"
        },
        doc : "$$ROOT"   // store the whole document, this is optional
    }
}, {
    $match : {
        equal : true   // filter to get documents only satisfy : "valueof(field1) == valueof(field2)"
    }
}]);