Suppose that I have a series of documents with the following format:
{
\"_id\": \"3_0\",
\"values\": [\"1\", \"2\"]
}
and I would l
Starting in Mongo 4.4
, the $function aggregation operator allows applying a custom javascript function to implement behaviour not supported by the MongoDB Query Language.
For instance, in order to concatenate an array of strings:
// { "_id" : "3_0", "values" : [ "1", "2" ] }
db.collection.aggregate(
{ $set:
{ "values":
{ $function: {
body: function(values) { return values.join('_'); },
args: ["$values"],
lang: "js"
}}
}
}
)
// { "_id" : "3_0", "values" : "1_2" }
$function
takes 3 parameters:
body
, which is the function to apply, whose parameter is the array to join.args
, which contains the fields from the record that the body
function takes as parameter. In our case "$values"
.lang
, which is the language in which the body
function is written. Only js
is currently available.