Reputation: 1238
i have a collection which i would like to update all of it's documents according to field email
and convert it to lower case.
const addressBookSchema = new Schema({
email: String,
});
const addressBook = mongoose.model("address_book", addressBookSchema)
i'm trying to do the following:
addressBook.update({}, {$set: {email: email.toLowerCase()}}, {multi: true});
But that doesn't work.
how do i get the email field and set it to lowercase?
Upvotes: 0
Views: 1127
Reputation: 103
By the below method you are able to update multiple document with lower case aggregate function.
db.addressBook.updateMany(
{},
[{$set : {email :{ $toLower: "$email" } }}],
)
Upvotes: 2
Reputation: 984
If you have such a large dataset, you should use the bulkWrite() function
addressBook.bulkWrite([
{
updateMany: {
filter: {},
update: { email: email.lowercase()}
}
},
]).then(handleResult);
Upvotes: 1
Reputation: 783
For doing it on all documents,
addressBook.find({}, {email: 1})
.exec((err, docs) => {
if (err || docs == undefined || docs.length == 0)
;
else {
docs.forEach((doc) => {
addressBook.findOneAndUpdate({_id: doc._id},
{$set: {email: doc.email.lowercase()}})
.exec();
});
}
});
Upvotes: 1