MongoDB $strcasecmp Operator Examples
To understand it better, let’s look at some examples of the MongoDB $strcasecmp Operator.
In the following examples, we are working with:
Database: w3wiki
Collection: employee
Document: three documents that contain the details of the employees in the form of field-value pairs.
Example 1: Using $strcasecmp Operator
In this example, we are going compare the value of the department field of all the documents present in employee collection with the “development” string using $strcasecmp operator.
Query:
db.employee.aggregate([
... {$project: {"name.first": 1, _id: 0, result:
... {$strcasecmp: ["$department", "development"]}}}])
Output:
Example 2: Using $strcasecmp Operator in the Embedded Document
In this example, we are going compare the value of the name.first field of all the documents present in employee collection with the “Sunita” string using $strcasecmp operator.
Query:
db.employee.aggregate([
... {$project: {result: {$strcasecmp: ["$name.first", "Sunita"]}}}])
Output:
MongoDB $strcasecmp Operator
MongoDB $strcasecmp operator performs a case-insensitive comparison between two strings.