Udate text to Title Case

60 views
Skip to first unread message

Mark McPartland

unread,
Nov 16, 2016, 5:53:51 PM11/16/16
to mongodb-user
Hi,
In our MongoDB we have a large number of documents that have inconsistent use of case in their title. 
Some are Sentence case, some are all upper case
"The Cat Jumped Down the Road"
"THE DOG SAT ON THE LOG"

Seeking assistance on how we could update all to be Title Case (First letter of each word in upper case, rest in lower case) to get:

"The Cat Jumped Down The Road"
"The Dog Sat On The Log"

cheers
Mark

Kevin Adistambha

unread,
Nov 21, 2016, 10:08:21 PM11/21/16
to mongodb-user

Hi Mark,

Seeking assistance on how we could update all to be Title Case (First letter of each word in upper case, rest in lower case)

One way to achieve this is to define a Javascript function that returns a title case in the mongo shell, e.g.:

function titleCase(x) {
    return x.split(' ').map(function(x) {
        return x[0].toUpperCase() + x.slice(1).toLowerCase()
    }).join(' ')
}

Then call the titleCase() function for each document in the collection, saving each modified document back into the collection. For example, using MongoDB 3.2.11:

> db.test.insert({a:'The Cat Jumped Down the Road'})
> db.test.insert({a:'THE DOG SAT ON THE LOG'})

> // Call the titleCase() function for each document, and save the new document
> db.test.find().forEach(function(doc) {
...     doc.a = titleCase(doc.a)
...     db.test.save(doc)
... })
Updated 1 existing record(s) in 1ms
Updated 1 existing record(s) in 1ms

> db.test.find()
{
  "_id": ObjectId("5833b3ac4e2ef0aa79003885"),
  "a": "The Cat Jumped Down The Road"
}
{
  "_id": ObjectId("5833b3ad4e2ef0aa79003886"),
  "a": "The Dog Sat On The Log"
}

Please note that the code snippet above was not extensively tested and only serves as an illustration of how this can be achieved in the mongo shell. Before doing any major maintenance which involves every document in your collection, please make sure that every procedure was tested and all backups are recent.

Best regards,
Kevin

Reply all
Reply to author
Forward
0 new messages