Introduction to MongoDB cursor.collation() Method

MongoDB is a popular document-oriented database, and the collation() method is used to specify a certain sorting rule when querying data. collation() refers to the rules for comparing strings. By specifying the sorting rules, the query results can be sorted according to the sorting rules of a certain language or country. This article will provide a detailed introduction to the collation() method in MongoDB.

Syntax

The syntax of the collation() method in MongoDB is as follows:

db.collection.find().collation({locale: "<locale>", strength: <strength>})

Parameter description:

  • locale: Specifies the locale, such as “en_US”, “fr_FR”, “zh”, etc., indicating the sorting rules of the specified region.
  • strength: Specifies the strength level, which can be 1, 2, or 3. The larger the number, the higher the accuracy of the sorting and the stricter the sorting rules.

Use Cases

Using the collation() method can sort the query results according to the specified sorting rules. When dealing with data in multiple languages or countries, using the collation() method can ensure the accuracy of the query results. For example, when querying Chinese data, the collation() method can use the sorting rules of Chinese to ensure the accuracy of the query results.

Example

The following example demonstrates how to use the collation() method to sort the query results according to the specified sorting rules.

Assume that the employees collection contains the following documents:

{ "_id" : ObjectId("617bd32a87e1708728eb61d1"), "name" : "Alice", "age" : 25 }
{ "_id" : ObjectId("617bd33487e1708728eb61d2"), "name" : "Lucy", "age" : 30 }
{ "_id" : ObjectId("617bd33c87e1708728eb61d3"), "name" : "James", "age" : 35 }

We want to query the employee information with the surname “Zhang” and sort it by name according to the Chinese sorting rules. The following command can be used:

db.employees
  .find({ name: /^Zhang/ })
  .collation({ locale: "zh", strength: 1 })
  .sort({ name: 1 })

After executing the above command, the following query result will be obtained:

{ "_id" : ObjectId("617bd32a87e1708728eb61d1"), "name" : "Alice", "age" : 25 }

Conclusion

The collation() method can sort the query results according to the specified sorting rules and ensure the accuracy of the query results. When querying data in multiple languages or countries, using the collation() method can avoid query errors caused by different sorting rules.