如何使用 $toLower 更新 MongoDB 集合?
MongoDB 中有一个 $toLower 运算符,可以作为聚合框架的一部分使用。但是,我们还可以使用 for 循环来迭代特定字段并逐个更新。
让我们先用文档创建一个集合
> db.toLowerDemo.insertOne({"StudentId":101,"StudentName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1b4515e86fd1496b38bf")
}
> db.toLowerDemo.insertOne({"StudentId":102,"StudentName":"Larry"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1b4b15e86fd1496b38c0")
}
> db.toLowerDemo.insertOne({"StudentId":103,"StudentName":"CHris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1b5115e86fd1496b38c1")
}
> db.toLowerDemo.insertOne({"StudentId":104,"StudentName":"ROBERT"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1b5a15e86fd1496b38c2")
}以下是使用 find() 方法显示集合中所有文档的查询
> db.toLowerDemo.find().pretty();
这将产生以下输出
{
"_id" : ObjectId("5c9b1b4515e86fd1496b38bf"),
"StudentId" : 101,
"StudentName" : "John"
}
{
"_id" : ObjectId("5c9b1b4b15e86fd1496b38c0"),
"StudentId" : 102,
"StudentName" : "Larry"
}
{
"_id" : ObjectId("5c9b1b5115e86fd1496b38c1"),
"StudentId" : 103,
"StudentName" : "CHris"
}
{
"_id" : ObjectId("5c9b1b5a15e86fd1496b38c2"),
"StudentId" : 104,
"StudentName" : "ROBERT"
}以下是使用 $toLower 更新 MongoDB 的查询
> db.toLowerDemo.find().forEach(
... function(lower) {
... lower.StudentName = lower.StudentName.toLowerCase();
... db.toLowerDemo.save(lower);
... }
... );让我们再次检查上述集合中的文档。以下是查询
> db.toLowerDemo.find().pretty();
这将产生以下输出
{
"_id" : ObjectId("5c9b1b4515e86fd1496b38bf"),
"StudentId" : 101,
"StudentName" : "john"
}
{
"_id" : ObjectId("5c9b1b4b15e86fd1496b38c0"),
"StudentId" : 102,
"StudentName" : "larry"
}
{
"_id" : ObjectId("5c9b1b5115e86fd1496b38c1"),
"StudentId" : 103,
"StudentName" : "chris"
}
{
"_id" : ObjectId("5c9b1b5a15e86fd1496b38c2"),
"StudentId" : 104,
"StudentName" : "robert"
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP