Starting in `Mongo 4.4`, for those that want to **compare sub-documents** and not only primitive values (since `{"a": "b"} == {"a": "b"}` is `false`), we can use the new [`$function`](
[To see links please register here]
) aggregation operator that allows applying a custom javascript function:
// { "a1" : { "x" : 1, "y" : 2 }, "a2" : { "x" : 1, "y" : 2 } }
// { "a1" : { "x" : 1, "y" : 2 }, "a2" : { "x" : 3, "y" : 2 } }
db.collection.aggregate(
{ $match:
{ $expr:
{ $function: {
body: function(a1, a2) { return JSON.stringify(a1) != JSON.stringify(a2); },
args: ["$a1", "$a2"],
lang: "js"
}}
}
}
)
// { "a1" : { "x" : 1, "y" : 2 }, "a2" : { "x" : 3, "y" : 2 } }
`$function` takes 3 parameters:
* `body`, which is the function to apply, whose parameter are the two fields to compare.
* `args`, which contains the fields from the record that the `body` function takes as parameter. In our case, both `"$a1"` and `"$a2"`.
* `lang`, which is the language in which the `body` function is written. Only `js` is currently available.