skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. I was getting TypeError: <collection-name>.update is not a function when I tried the accepted answer on mongodb 5.1.0, so I did it using the below code.

    const products = db.collection("Products");
    
    await products.updateMany({},
    [
      {
        $set: {
          slug: {
            "$replaceAll": {
              input: {
                $toLower: "$name"
              },
              find: " ",
              replacement: "-"
            }
          }
        }
      }
    ])
    

    replace $name with the property of which you want to create slug.
    Also, don’t forget to replace the collection name with yours ;D

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search