让我们首先创建一个包含文档的集合,其中一个字段是StudentName-
> db.lowerCaseDemo.insertOne({"StudentName":"JOHN SMith"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9a86fb50a6c6dd317ad9f") } > db.lowerCaseDemo.insertOne({"StudentName":"CAROL TAYLor"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9a88fb50a6c6dd317ada0") } > db.lowerCaseDemo.insertOne({"StudentName":"DAVID Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9a89fb50a6c6dd317ada1") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.lowerCaseDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd9a86fb50a6c6dd317ad9f"), "StudentName" : "JOHN SMith" } { "_id" : ObjectId("5cd9a88fb50a6c6dd317ada0"), "StudentName" : "CAROL TAYLor" } { "_id" : ObjectId("5cd9a89fb50a6c6dd317ada1"), "StudentName" : "DAVID Miller" }
以下是要实现的查询toLowerCase()
-
> db.lowerCaseDemo.find({StudentName: { $exists: true}}).forEach( function(v) { v.StudentName = v.StudentName.toLowerCase(); db.lowerCaseDemo.save(v); } );
让我们再次检查所有文件-
> db.lowerCaseDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd9a86fb50a6c6dd317ad9f"), "StudentName" : "john smith" } { "_id" : ObjectId("5cd9a88fb50a6c6dd317ada0"), "StudentName" : "carol taylor" } { "_id" : ObjectId("5cd9a89fb50a6c6dd317ada1"), "StudentName" : "david miller" }