在 MongoDB 中實現字串比較?
要在 MongoDB 中實現字串比較,請使用 $strcasecmp。它對兩個字串執行不區分大小寫的比較。它返回 −
如果第一個字串“大於”第二個字串,則返回 1。
如果兩個字串相等,則返回 0。
如果第一個字串“小於”第二個字串,則返回 -1。
讓我們建立一個包含文件的集合 −
> db.demo490.insertOne({"Name1":"John","Name2":"john"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8496ccb0f3fa88e22790bb")
}
> db.demo490.insertOne({"Name1":"David","Name2":"Bob"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8496d9b0f3fa88e22790bc")
}
> db.demo490.insertOne({"Name1":"Carol","Name2":"Carol"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e8496e5b0f3fa88e22790bd")
}在集合中顯示所有文件,可以使用 find() 方法 −
> db.demo490.find();
這將產生以下輸出 −
{ "_id" : ObjectId("5e8496ccb0f3fa88e22790bb"), "Name1" : "John", "Name2" : "john" }
{ "_id" : ObjectId("5e8496d9b0f3fa88e22790bc"), "Name1" : "David", "Name2" : "Bob" }
{ "_id" : ObjectId("5e8496e5b0f3fa88e22790bd"), "Name1" : "Carol", "Name2" : "Carol" }以下是關於在 MongoDB 中實現字串比較的查詢 −
> db.demo490.aggregate(
... [
... {
... $project:
... {
... Name1: 1,
... Name2: 1,
... Result: { $strcasecmp: [ "$Name1", "$Name2" ] }
... }
... }
... ]
... )這將產生以下輸出 −
{ "_id" : ObjectId("5e8496ccb0f3fa88e22790bb"), "Name1" : "John", "Name2" : "john", "Result"
: 0 }
{ "_id" : ObjectId("5e8496d9b0f3fa88e22790bc"), "Name1" : "David", "Name2" : "Bob",
"Result" : 1 }
{ "_id" : ObjectId("5e8496e5b0f3fa88e22790bd"), "Name1" : "Carol", "Name2" : "Carol",
"Result" : 0 }
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP