Home > database >  How to generate a slug for documents that already exist in MongoDB?
How to generate a slug for documents that already exist in MongoDB?

Time:09-09

My MongoDB database is very large (about 10 million items using 1000 MB of disk space), but it's documents do not have a slug based on the title. Currently a document looks like this:

{
  "_id": {
    "$oid": "630f3c32c1a580642a9ff4a0"
  },
  "title": "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",
  "Post": "this is a post"
}

CodePudding user response:

You can use $replaceAll and $toLower inside an update pipeline for this:

db.collection.update(
  {},
  [{$set: {
      slug: {
        $replaceAll: {
          input: {$toLower: "$title"},
          find: " ",
          replacement: "-"
        }
      }
  }}],
  {multi: true}
)

See how it works on the playground example

  • Related