在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 }