使用$ toLower更新MongoDB集合 [英] Update MongoDB collection using $toLower

查看:117
本文介绍了使用$ toLower更新MongoDB集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含用户名的现有MongoDB集合.用户名包含小写字母和大写字母.

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);
 }
)

推荐答案

MongoDB没有将$toLower作为命令的概念.解决方案是对数据运行一个大的for循环并单独发布更新.

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.

您可以在任何驱动程序中或从Shell中执行以下操作:

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.

雷蒙(Remon)提出了一个很好的观点. $toLower命令确实作为聚合框架的一部分存在,但这与更新无关.用于更新的文档位于此处.

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.

这篇关于使用$ toLower更新MongoDB集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆