The following query can do the trick. We are using $reduce to replace space with a hyphen.
db.collection.aggregate([
{
$addFields:{
"slug":{
$let:{
"vars":{
"array":{
$split:["$title"," "]
}
},
"in":{
$reduce:{
"input":"$$array",
"initialValue":"",
"in":{
$concat:["$$value","-","$$this"]
}
}
}
}
}
}
},
{
$addFields:{
"slug":{
$substr:["$slug",1,{ $strLenBytes: "$slug" }]
}
}
}
]).pretty()
Data set:
{
"_id" : ObjectId("5d84af0aebcbd560107c54af"),
"title" : "This is my 1st adventure"
}
{
"_id" : ObjectId("5d84af0aebcbd560107c54b0"),
"title" : "This is my 2nd adventure"
}
Output:
{
"_id" : ObjectId("5d84af0aebcbd560107c54af"),
"title" : "This is my 1st adventure",
"slug" : "This-is-my-1st-adventure"
}
{
"_id" : ObjectId("5d84af0aebcbd560107c54b0"),
"title" : "This is my 2nd adventure",
"slug" : "This-is-my-2nd-adventure"
}