Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB toLowerCase()

I have a collection called Profiles, which contains an array called emails.

I want to change all the email strings in the array to lowercase.

db.Profiles.update({"emails":/@/i}, {$set: {"emails" : emails.toLowerCase()}}})

Error:

Tue Jan 29 16:52:28 SyntaxError: missing ) after argument list (shell):1

I also found this:

db.Profiles.find().forEach(
  function(e) {
    e.emails = e.emails.toLowerCase();
    db.Profiles.save(e);
  }
)

Error:

Tue Jan 29 16:51:41 TypeError: e.emails.toLowerCase is not a function (shell):3

Thanks in advance for any help.

like image 867
Fruitful Avatar asked Dec 01 '25 04:12

Fruitful


2 Answers

You need to lowercase every string inside emails array. There's no toLowerCase function in string[].

Example:

db.Profiles.find().forEach(
   function(e) {
      for(var i = 0; i < e.emails.length; i++){ 
         e.emails[i] = e.emails[i].toLowerCase(); 
      }
      db.Profiles.save(e);  
});
like image 100
Duarte Madueño Avatar answered Dec 02 '25 19:12

Duarte Madueño


I found an easier and faster method

db.Profiles.find({email : { $exists: true}}).forEach(
 function(e) {
   e.email = e.email.toLowerCase();
    db.Profiles.save(e);
 });
like image 40
user2654744 Avatar answered Dec 02 '25 17:12

user2654744



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!