$function(aggregation)

db.players.insertMany([
   { _id: 1, name: "Miss Cheevous",  scores: [ 10, 5, 10 ] },
   { _id: 2, name: "Miss Ann Thrope", scores: [ 10, 10, 10 ] },
   { _id: 3, name: "Mrs. Eppie Delta ", scores: [ 9, 8, 8 ] }
]); db.players.find( {$expr: { $function: {
      body: function(name) { return hex_md5(name) == "15b0a220baa16331e8d80e15367677ad"; },
      args: [ "$name" ],
      lang: "js"
} } } ); 
Error: error:  {
"ok" : 0,
"err msg" :  "Unrecognised expression '$function'"",
"code" : 168,
"codeName" : "InvalidPipeline Operator" 
}

Above is the error while making query on collection , ‘players’.

Hi Arindam,

You can only use the $function aggregator within an $aggregation expression. So instead of db.players.find try: db.players.aggregate().

I wrote a blog post that goes into it a lot more that you can find here: https://www.mongodb.com/how-to/use-function-accumulator-operators/ :slight_smile:

1 Like

ok, I get the same output with 1. $where and $function 2. $expr and $function operator which are used for querying the collection.
I have another query. - how to add md5 hash value in mongodb collections?
In the above example hex_md5(name) == “15b0a220baa16331e8d80e15367677ad”
How do we get this 32 digits hexadecimal number?

When I run this I get back:

 { "_id" : 2, "name" : "Miss Ann Thrope", "scores" : [ 10, 10, 10 ] }

Is it possible you’re not connecting to the correct version of MongoDB? $function was introduced in 4.4.

I get your point. But , still you didn’t tell me the specification for incorporating hex_md5 method in MongoDB Shell.
How do you get hex_md5 = “15b0a220baa16331e8d80e15367677ad” ? Any hexadecimal 32 digits can not be used instead.

Your example code uses $function in the query predicate to test for equality with md5. If you want to return md5 then you need to use $function in the projection part of the query to create the new field. You can do this with aggregate command in 4.2 or if you are already on 4.4 you can just use aggregation expressions in find. Using the same sample data:

 > db.players.find( {},  {name:1, md5: { $function: {  body: function(name) { return hex_md5(name); },   args: [ "$name" ],   lang: "js" } } } );
{ "_id" : 1, "name" : "Miss Cheevous", "md5" : "5e89555bdf7601c64b5f7984a76bf7a0" }
{ "_id" : 2, "name" : "Miss Ann Thrope", "md5" : "15b0a220baa16331e8d80e15367677ad" }
{ "_id" : 3, "name" : "Mrs. Eppie Delta ", "md5" : "fe698b4989844ab8d786ad263c5d7350" }