Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

Update MongoDB collection using $toLower

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);
 }
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...