JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Case insensitive query in MongoDB

Author:JIYIK Last Updated:2025/04/27 Views:

In this article, case insensitive queries are discussed briefly and in detail. Also, case insensitive search queries are explained in detail.

This article discusses the following topics.

  1. Case-insensitive search
  2. Improve case-insensitive regular expression queries
  3. find()Use regular expressions for case-insensitive searches in the

Case insensitive query in MongoDB

Case-insensitive indexes support searches that compare strings without regard to case.

You db.collection.createIndex()can create a case-insensitive index by including the collation parameter as an optional parameter.

db.collection.createIndex( { "key" : 1 },
                           { collation: {
                               locale : <locale>,
                               strength : <strength>
                             }
                           } )

Include the following when specifying a collation for a case-sensitive index.

  1. locale - specifies the language rules.
  2. strength - used to determine the comparison rule. A value of 1 or 2 will indicate a case-insensitive sorting rule.

Behavior:

Using a case-insensitive index does not affect query results; however, it can improve speed.

To use an index specified by a collation, queries and sort operations must use the same collation as the index. If a collection defines a collation, all queries and indexes using the collection inherit it unless they specify a different collation.

Creating a case-insensitive index

To use a case-insensitive index on a collection that does not have a default collation, create an index with a collation and specify the strength option as 1 or 2. To use an index-level collation, you must provide the same collation at the query level.

The following example generates a collection with no default collation and adds an index with a case-insensitive collation to the type column.

db.createCollection("fruit")

db.fruit.createIndex( { type: 1},
                      { collation: { locale: `en`, strength: 2 } } )

The query must have the same collation to use the index.

db.fruit.insertMany( [
   { type: "bloctak" },
   { type: "Bloctak" },
   { type: "BLOCTAK" }
] )

db.fruit.find( { type: "bloctak" } )
//not use index, finds one result

db.fruit.find( { type: "bloctak" } ).collation( { locale: `en`, strength: 2 } )
// uses index, and will find three results

db.fruit.find( { type: "bloctak" } ).collation( { locale: `en`, strength: 1 } )
//not uses the index, finds three results

Case-Insensitive Indexes on Collections Using the Default Collation If you establish a collection using the default collation, all future indexes inherit that collation unless you provide a different collation. All queries that do not specify a collation inherit the default collation.

The following example generates a collection of names with the default collation and then creates an index on the first_name field.

db.createCollection("names", { collation: { locale: `en_US`, strength: 2 } } )

db.names.createIndex( { first_name: 1 } ) // inherits the default collation

Insert a small section of the name:

db.names.insertMany( [
   { first_name: "Betsy" },
   { first_name: "BETSY"},
   { first_name: "betsy"}
] )

By default, queries against this collection use the provided collation and, if possible, an index.

db.names.find( { first_name: "betsy" } )
// inherits the default collation: { collation: { locale: `en_US`, strength: 2 } }
// finds three results

The preceding procedure finds all three documents using the collection's default collation. It uses an index on the first_name field for efficiency.

The collection may still perform case-sensitive searches by specifying a different collation in the query.

db.names.find( { first_name: "betsy" } ).collation( { locale: `en_US` } )
// not use the collection`s default collation, finds one result

The preceding procedure returns only one document because it uses a collation for which no strength value is provided. It does not use the default collation for the index or collection.


Improve case-insensitive regular expression queries

If you frequently perform case-insensitive regular expression queries (using the I option), you should create a case-insensitive index to accommodate your searches.

A collation on an index can be used to provide language-specific string comparison rules, such as rules for letter case and accents. A case-insensitive index significantly improves the performance of case-insensitive queries.

Consider the following document in the employees collection. _idThis collection contains no indexes other than the usual index.

db={
  "employees": [
    {
      "_id": 1,
      "first_name": "Hannah",
      "last_name": "Simmons",
      "dept": "Engineering"
    },
    {
      "_id": 2,
      "first_name": "Michael",
      "last_name": "Hughes",
      "dept": "Security"
    },
    {
      "_id": 3,
      "first_name": "Wendy",
      "last_name": "Crawford",
      "dept": "Human Resources"
    },
    {
      "_id": 4,
      "first_name": "MICHAEL",
      "last_name": "FLORES",
      "dept": "Sales"
    }
  ]
}

If your application frequently searches the first_name column, you might want to use a case-insensitive regular expression query to discover matching names.

Case-insensitive regular expressions are also helpful in matching different data formats, such as the example above where your first_name is Michael and MICHAEL.

If the user searches for michael, the program might execute the following query.

db.employees.find({
  first_name: {
    $regex: "michael",
    $options: "i"
  }
})

Because this query contains $regex:

{ "_id" : 2, "first_name" : "Michael", "last_name" : "Hughes", "dept" : "Security" }
{ "_id" : 4, "first_name" : "MICHAEL", "last_name" : "FLORES", "dept" : "Sales" }

Although this query returns the desired documents, case-insensitive regular expression queries are slow without supported indexes. You can improve efficiency by creating a case-insensitive index on the first_name field.

db.employees.createIndex(
  { first_name: 1 },
  { collation: { locale: 'en', strength: 2 } }
)

When indexing collated documents with the strength field set to 1 or 2, the index is case-insensitive to allow for a broader interpretation of collated documents and various strength values.

For applications to use the index, you must also mention the index's collation document in your queries. Remove the $regex operator from the previous db.collection.find() function and use the newly constructed index instead.

db.employees.find( { first_name: "michael" } ).collation( { locale: 'en', strength: 2 } )

Do not use the $regex operator when using a case-insensitive index for a query. The $regex implementation does not support collations and cannot use case-insensitive indexes.


Use regular expressions in find() method to do case insensitive search in MongoDB

Use regular expressions in find()the method to perform a case-insensitive search.

grammar:

db.demo572.find({"yourFieldName" : { `$regex`:/^yourValue$/i}});

To understand the above syntax, let us create a document collection.

> db.demo572.insertOne({"CountryName":"US"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f0e581e9acd78b427f1")
}
> db.demo572.insertOne({"CountryName":"UK"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f17581e9acd78b427f2")
}
> db.demo572.insertOne({"CountryName":"Us"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f1b581e9acd78b427f3")
}
> db.demo572.insertOne({"CountryName":"AUS"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f20581e9acd78b427f4")
}
> db.demo572.insertOne({"CountryName":"us"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e915f25581e9acd78b427f5")
}

find()The function displays all documents in a collection.

db.demo572.find();

This will produce the following output.

Case insensitive search in MongoDB

Following is the query for case insensitive search.

> db.demo572.find({"CountryName" : { `$regex`:/^US$/i}});

This will produce the following output.

Case-insensitive search in MongoDB 2

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Querying documents with array size greater than 1 in MongoDB

Publish Date:2025/04/27 Views:154 Category:MongoDB

When working with projects where you need to validate the size of an array or find elements whose size is greater or less than a certain length, you might use MongoDB operators such as $size, $where, $exists, etc. The methods discussed belo

MongoDB starts with a query

Publish Date:2025/04/10 Views:196 Category:MongoDB

In this MongoDB article, users will learn how to start queries using $regex. It provides regular expression functionality for pattern matching strings in queries. MongoDB starts querying using $regex If you want to use $regex , use one of t

Query with OR condition in MongoDB

Publish Date:2025/04/10 Views:190 Category:MongoDB

This article will explain how to use the $or operator in MongoDB queries. MongoDB provides users with different types of logical query operators, and the $or operator is one of them. This operator performs a logical OR operation on an array

MongoDB 从查询开始

Publish Date:2023/05/11 Views:188 Category:MongoDB

在这篇 MongoDB 文章中,用户将学习如何使用 $regex 进行开始查询。 它为查询中的模式匹配字符串提供正则表达式功能。

MongoDB 中带有 OR 条件的查询

Publish Date:2023/05/11 Views:218 Category:MongoDB

$or 运算符用于对由两个或多个表达式组成的数组执行逻辑或运算,并仅选择或检索与数组中给定的至少一个表达式匹配的文档。MongoDB 中的 $or 运算符

MongoDB 中查询数组大小大于1的文档

Publish Date:2023/05/10 Views:473 Category:MongoDB

在处理需要验证数组大小或查找大小大于或小于特定长度的元素的项目时,可能会使用 $size、$where、$exists 等 MongoDB 运算符。下面讨论的方法可以帮助您解决数组长度或数组大小问题。

MongoDB 中不区分大小写的查询

Publish Date:2023/05/10 Views:193 Category:MongoDB

在本文中,将简要详细地讨论不区分大小写的查询。 此外,还详细解释了不区分大小写的搜索查询。MongoDB 中不区分大小写的查询

在 MongoDB 中使用多个条件进行查询

Publish Date:2023/05/10 Views:1195 Category:MongoDB

本文将教您如何使用 MongoDB 中的多个文档进行多条件查询。 $and 和 $or 运算符通过每个示例进行了简要说明。MongoDB 为用户提供了不同的逻辑查询操作符,$or 和$and 操作符是其一。

MongoDB 查询嵌套对象

Publish Date:2023/05/10 Views:222 Category:MongoDB

在本篇文章中,我们将学习如何查询 MongoDB 中的嵌套对象。在 MongoDB 中查询嵌套对象 MongoDB 提供读取操作以从集合中检索嵌入或嵌套数据或搜索嵌入或嵌套文档。

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial