David Spira
David Spira

Reputation: 153

mongodb replace one character in many documents

I have this collection in a database, it contains a lot of documents on it, i would like all instances of "Æ" to be replaced with "ae".

My documents look like this:

{ 
    "_id" : ObjectId("57071e9fee31902f0a9ad989"),
    "layout" : "normal", 
    "name" : "Æther Flash", 
    "manaCost" : "{2}{R}{R}", 
    "cmc" : 4,
    "colors" : [ "Red" ]
}

I suppose i should use something like find_one_and_update, maybe?

Upvotes: 0

Views: 506

Answers (1)

martskins
martskins

Reputation: 2940

This should work. It may take a while depending on how big you db is, which might be big considering its a MTG db ;), but it should work.

db.getCollection('AllCards').find({$or: [{name: {$regex: 'Æ'}}, {name: {$regex: 'æ'}}]}).forEach(function (x) {
    x.name = x.name.replace(/Æ/g, 'Ae').replace(/æ/g, 'ae');

    db.getCollection('AllCards').save(x);
});

Of course that only covers Æs in the name. But I suppose you can sort out how to make it work with all necessary fields.

Upvotes: 3

Related Questions