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

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.