[英]How to use regex in addFields aggregate with mongodb
我想在 addFiels 中使用正则表达式和 mongodb,但我无法做到这一点,下面是我尝试过的代码
$addFields: {slug: {$title: {$regex: '/^[^_s]*$/'}}}
但这是给 mongo 错误。 请找我解决。 我预期的 output 应该是slug: "This-is-my-1st-adventure"
。 在我的数据库title: "This is my 1st adventure"
以下查询可以解决问题。 我们使用$reduce用连字符替换空格。
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()
数据集:
{
"_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"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.