MongoDB $strcasecmp Operator
MongoDB provides different types of string expression operators that are used in the aggregation pipeline stages $strcasecmp operator is one of them. This operator is used to perform a case-insensitive comparison of two strings and return the following result according to the condition:
- If the first string is greater than the second string, then this operator will return 1.
- If the first string is less than the second string, then this operator will return -1.
- If both the strings are equal, then this operator will return 0.
Syntax:
{ $strcasecmp: [ <expression1>, <expression2> ] }
Here, the arguments passed in this operator can be any valid expression until they resolve to strings.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: employee
Document: three documents that contain the details of the employees in the form of field-value pairs.
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.
db.employee.aggregate([ ... {$project: {"name.first": 1, _id: 0, result: ... {$strcasecmp: ["$department", "development"]}}}])
Using $strcasecmp Operator in the Embedded Document:
n 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.
db.employee.aggregate([ ... {$project: {result: {$strcasecmp: ["$name.first", "Sunita"]}}}])
Please Login to comment...