Search code examples
mongodbmongoosemongodb-querynosqlslug

How to add a random number in slug that already exists in MongoDB?


Currently a document looks like this:

{
  "_id": {
    "$oid": "630f3c32c1a580642a9ff4a0"
  },
  "title": "This is a title",
  "slug": "this-is-a-title",
  "Post": "this is a post"
}

But I want it like this:

{
  "_id": {
    "$oid": "630f3c32c1a580642a9ff4a0"
  },
  "title": "This is a title",
  "slug": "this-is-a-title-548631",
  "Post": "this is a post"
}

How can I add a 6 digit random number at the end of slug in all documents?


Solution

  • You can use $rand to generate a random number, combined with some other operators you can force the 6 digits constraint, like so:

    db.collection.updateMany({},
    [
      {
        $set: {
          slug: {
            $concat: [
              "$slug",
              "-",
              {
                $toString: {
                  $round: {
                    $add: [
                      {
                        $multiply: [
                          {
                            $rand: {}
                          },
                          899999
                        ]
                      },
                      100000
                    ]
                  }
                }
              }
            ]
          }
        }
      }
    ])
    

    Mongo Playground

    (this will gives results in the range of 100,000 to 999,999), if you want to allow 0 prefixes, like 000123 then you can still use the same approach and pad with zeros based on the number length.