Implementing String Comparison in MongoDB?


To implement string comparison in MongoDB, use $strcasecmp. It performs case-insensitive comparison of two strings. It returns −

  • 1 if first string is “greater than” the second string.

  • 0 if the two strings are equal.

  • -1 if the first string is “less than” the second string.

Let us create a collection with documents −

> 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")
}

Display all documents from a collection with the help of find() method −

> db.demo490.find();

This will produce the following output −

{ "_id" : ObjectId("5e8496ccb0f3fa88e22790bb"), "Name1" : "John", "Name2" : "john" }
{ "_id" : ObjectId("5e8496d9b0f3fa88e22790bc"), "Name1" : "David", "Name2" : "Bob" }
{ "_id" : ObjectId("5e8496e5b0f3fa88e22790bd"), "Name1" : "Carol", "Name2" : "Carol" }

Following is the query to implement string comparison in MongoDB −

> db.demo490.aggregate(
... [
...    {
...       $project:
...       {
...          Name1: 1,
...          Name2: 1,
...          Result: { $strcasecmp: [ "$Name1", "$Name2" ] }
...       }
...    }
... ]
... )

This will result the following output −

{ "_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 }

Updated on: 11-May-2020

516 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements