MongoDB – Update to upper case

A document, and you want to update all the ‘source’ values to UPPERCASE.

whois.json
{
	"_id" : NumberLong(1),
	"country" : "au",
	"source" : "apnic"
}
{
	"_id" : NumberLong(2),
	"country" : "cn",
	"source" : "apnic"
}
{
	"_id" : NumberLong(3),
	"country" : "us",
	"source" : "arin"
}

Solution

No sure if there is any ready function, but you can write a script to update the value to uppercase :


db.whois.find({ "source": { "$exists": true } }).forEach(function(doc) {
    db.whois.update(
        { "_id": doc._id },
        { "$set": { "source": doc.source.toUpperCase() } }
    );
});

Output

whois.json
{
	"_id" : NumberLong(1),
	"country" : "au",
	"source" : "APNIC",
}
{
	"_id" : NumberLong(2),
	"country" : "cn",
	"source" : "APNIC",
}
{
	"_id" : NumberLong(3),
	"country" : "us",
	"source" : "ARIN",
}

Done.

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
felipe
6 years ago

gracias 😀

esallenave
7 years ago

Hello,
Many thanks for this tip.
Would you be kind to tell us how to update ALL fields in a collection to uppercase ?
Cheers – Eric