I have a collection which elements can be simplified to this:
{tags : [1, 5, 8]}
where there would be at least one element in array and all of t
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.
And coupled with improvements made to db.collection.update() in Mongo 4.2
that can accept an aggregation pipeline, allowing the update of a field based on its own value,
We can manipulate and update an array in ways the language doesn't easily permit:
// { "tags" : [ 1, 5, 8 ] }
db.collection.updateMany(
{ tags: 1 },
[{ $set:
{ "tags":
{ $function: {
body: function(tags) { tags.push(2); return tags.filter(x => x != 1); },
args: ["$tags"],
lang: "js"
}}
}
}]
)
// { "tags" : [ 5, 8, 2 ] }
$function
takes 3 parameters:
body
, which is the function to apply, whose parameter is the array to modify. The function here simply consists in push
ing 2
to the array and filter
ing out 1
.args
, which contains the fields from the record that the body
function takes as parameter. In our case, "$tag"
.lang
, which is the language in which the body
function is written. Only js
is currently available.