Skip to content

Instantly share code, notes, and snippets.

@anton-x-t
Created May 3, 2024 17:26
Show Gist options
  • Save anton-x-t/eacf8ad0050069fc152eae85cc187f48 to your computer and use it in GitHub Desktop.
Save anton-x-t/eacf8ad0050069fc152eae85cc187f48 to your computer and use it in GitHub Desktop.
MongoDB Bulk Rename mongosh js
// MIT License
// Sources below!!! Thank you persons and entities for your code!!!
db.product.find({"fieldOne":"findString"}).forEach(doc => {
let updatedFieldOne = doc.fieldOne.replace('findString', 'replaceString');
print(doc._id)
print(doc.fieldOne)
print(updatedFieldOne)
db.product.updateOne(
{ "_id": doc._id },
{ $set : { "fieldOne" : updatedFieldOne } }
);
sleep(1200);
});
db.product.find({"fieldTwo":/findString/}).forEach(doc => {
let updatedFieldTwo = doc.fieldTwo.replace('findString', 'replaceString');
print(doc._id)
print(doc.fieldTwo)
print(updatedFieldTwo)
db.product.updateOne(
{ "_id": doc._id },
{ $set : { "fieldTwo" : updatedFieldTwo } }
);
sleep(1200);
});
// Sources:
// How to replace substring in mongodb document,
// thank you Lukas Liesis,
// https://stackoverflow.com/a/38575230/6533028
// How to replace substring in mongodb document,
// thank you Xavier Guihot,
// https://stackoverflow.com/a/56556298/6533028
// How to replace substring in mongodb document,
// thank you Naveed et al,
// https://stackoverflow.com/a/31262746/6533028
// MongoDB, $set,
// thank you MongoDB, Inc.,
// https://www.mongodb.com/docs/manual/reference/operator/update/set/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment