0

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"

1
  • can show show the whole error message, and the input [sample data] including the query. Commented Sep 20, 2019 at 10:52

1 Answer 1

2

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"
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.