如何使用 $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