Update MongoDB collection using $toLower

2019-01-11 10:08发布

问题:

I have an existing MongoDB collection containing user names. The user names contain both lower case and upper case letters. I want to update all the user names so they only contain lower case letters. I have tried this script, but it didn't work

db.myCollection.find().forEach(
 function(e) {
 e.UserName = $toLower(e.UserName);
 db.myCollection.save(e);
 }
)

Any information on getting this to work will be really appreciated, Scott

回答1:

MongoDB does not have a concept of $toLower as a command. The solution is to run a big for loop over the data and issue the updates individually.

You can do this in any driver or from the shell:

db.myCollection.find().forEach(
  function(e) {
    e.UserName = e.UserName.toLowerCase();
    db.myCollection.save(e);
  }
)

You can also replace the save with an atomic update:

db.myCollection.update({_id: e._id}, {$set: {UserName: e.UserName.toLowerCase() } })

Again, you could also do this from any of the drivers, the code will be very similar.


EDIT: Remon brings up a good point. The $toLower command does exist as part of the aggregation framework, but this has nothing to do with updating. The documentation for updating is here.



回答2:

Very similar solution but this worked me in new mongo 3.2 Execute the following in Mongo Shell or equivalent DB tools like MongoChef!

db.tag.find({hashtag :{ $exists:true}}).forEach(
 function(e) {
   e.hashtag = e.hashtag.toLowerCase();
   db.tag.save(e);
});


回答3:

With the accepted solution I know its very trivial to do the same for an array of elements, just in case

db.myCollection.find().forEach(
   function(e) {
      for(var i = 0; i < e.articles.length; i++) { 
          e.articles[i] = e.articles[i].toLowerCase(); 
      }
      db.myCollection.save(e); 
   }
)


回答4:

Just a note to make sure the field exists for all entries in your collection. If not you will need an if statement, like the following:

if (e.UserName) e.UserName = e.UserName.toLowerCase();


标签: mongodb