Open In App

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:

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

Article Tags :