Rakesh
Rakesh

Reputation: 178

How to use regex in addFields aggregate with mongodb

I want to use regex in addFiels in aggregate with mongodb, but I am not able to do that below is my code which I have tried

$addFields: {slug: {$title: {$regex: '/^[^_s]*$/'}}}

but this is giving mongo error. Please find me solution. My expected output should be slug: "This-is-my-1st-adventure". In my db title: "This is my 1st adventure"

Upvotes: 0

Views: 717

Answers (1)

Himanshu Sharma
Himanshu Sharma

Reputation: 3010

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"
}

Upvotes: 2

Related Questions