如何使用$ 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"
}以下是更新MongoDB的查询,例如$toLower
> 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"
}