Collation

New in version 3.4.

Collation allows users to specify language-specific rules for stringcomparison, such as rules for lettercase and accent marks.

You can specify collation for a collection or a view, an index, orspecific operations that support collation.

Collation Document

A collation document has the following fields:

  1. {
  2. locale: <string>,
  3. caseLevel: <boolean>,
  4. caseFirst: <string>,
  5. strength: <int>,
  6. numericOrdering: <boolean>,
  7. alternate: <string>,
  8. maxVariable: <string>,
  9. backwards: <boolean>
  10. }

When specifying collation, the locale field is mandatory; allother collation fields are optional. For descriptions of the fields,see Collation Document.

Default collation parameter values vary depending on whichlocale you specify. For a complete list of default collationparameters and the locales they are associated with, seeCollation Default Parameters.

FieldTypeDescription
localestringThe ICU locale. See Supported Languages and Locales for alist of supported locales.To specify simple binary comparison, specify locale value of"simple".
strengthintegerOptional. The level of comparison to perform.Corresponds to ICU Comparison Levels.Possible values are:
ValueDescription
1Primary level of comparison. Collation performscomparisons of the base characters only, ignoring otherdifferences such as diacritics and case.
2Secondary level of comparison. Collation performs comparisonsup to secondary differences, such as diacritics.That is, collation performs comparisons of base characters(primary differences) and diacritics (secondary differences).Differences between base characters takes precedence oversecondary differences.
3Tertiary level of comparison. Collation performs comparisonsup to tertiary differences, such as case and letter variants.That is, collation performs comparisons of base characters(primary differences), diacritics (secondary differences), andcase and variants (tertiary differences). Differences betweenbase characters takes precedence over secondary differences,which takes precedence over tertiary differences.This is the default level.
4Quaternary Level. Limited for specific use case toconsider punctuation when levels 1-3 ignore punctuationor for processing Japanese text.
5Identical Level. Limited for specific use case of tiebreaker.

See ICU Collation: Comparison Levelsfor details.

caseLevelbooleanOptional. Flag that determines whether to include case comparison atstrength level 1 or 2.

If true, include case comparison; i.e.

  • When used with strength:1, collation compares base charactersand case.
  • When used with strength:2, collation compares base characters,diacritics (and possible other secondary differences) and case.

If false, do not include case comparison at level 1 or2. The default is false.

For more information, see ICU Collation: Case Level.

caseFirststringOptional. A field that determines sort order of case differences duringtertiary level comparisons.

Possible values are:

ValueDescription
“upper”Uppercase sorts before lowercase.
“lower”Lowercase sorts before uppercase.
“off”Default value. Similar to "lower" with slightdifferences. Seehttp://userguide.icu-project.org/collation/customizationfor details of differences.

numericOrderingbooleanOptional. Flag that determines whether to compare numeric strings as numbersor as strings.

If true, compare as numbers; i.e. "10" is greater than"2".

If false, compare as strings; i.e. "10" is less than "2".

Default is false.

alternatestringOptional. Field that determines whether collation should consider whitespaceand punctuation as base characters for purposes of comparison.

Possible values are:

ValueDescription
"non-ignorable"Whitespace and punctuation are considered base characters.
"shifted"Whitespace and punctuation are not considered base charactersand are only distinguished at strength levels greater than 3.

See ICU Collation: Comparison Levelsfor more information.

Default is "non-ignorable".

maxVariablestringOptional. Field that determines up to which characters are consideredignorable when alternate: "shifted". Has no effect ifalternate: "non-ignorable"

Possible values are:

ValueDescription
"punct"Both whitespaces and punctuation are “ignorable”, i.e. notconsidered base characters.
"space"Whitespace are “ignorable”, i.e. not considered basecharacters.

backwardsbooleanOptional. Flag that determines whether strings with diacritics sort from backof the string, such as with some French dictionary ordering.

If true, compare from back to front.

If false, compare from front to back.

The default value is false.

normalizationbooleanOptional. Flag that determines whether to check if text require normalizationand to perform normalization. Generally, majority of text does notrequire this normalization processing.

If true, check if fully normalized and perform normalization tocompare text.

If false, does not check.

The default value is false.

Seehttp://userguide.icu-project.org/collation/concepts#TOC-Normalization for details.

Operations that Support Collation

You can specify collation for the following operations:

Note

You cannot specify multiple collations for an operation. Forexample, you cannot specify different collations per field, or ifperforming a find with a sort, you cannot use one collation for thefind and another for the sort.

Commandsmongo Shell Methods
createdb.createCollection()db.createView()
createIndexes[1]db.collection.createIndex()[1]
aggregatedb.collection.aggregate()
distinctdb.collection.distinct()
findAndModifydb.collection.findAndModify()db.collection.findOneAndDelete()db.collection.findOneAndReplace()db.collection.findOneAndUpdate()
findcursor.collation() to specify collation fordb.collection.find()
mapReducedb.collection.mapReduce()
deletedb.collection.deleteOne()db.collection.deleteMany()db.collection.remove()
updatedb.collection.update()db.collection.updateOne(),db.collection.updateMany(),db.collection.replaceOne()
shardCollectionsh.shardCollection()
countdb.collection.count()
Individual update, replace, and delete operations indb.collection.bulkWrite().
[1](1, 2) Some index types do not support collation. SeeCollation and Unsupported Index Types for details.

Behavior

Local Variants

Some collation locales have variants, which employ speciallanguage-specific rules. To specify a locale variant, use the followingsyntax:

  1. { "locale" : "<locale code>@collation=<variant>" }

For example, to use the pinyin variant of the Chinese collation:

  1. { "locale" : "zh@collation=pinyin" }

For a complete list of all collation locales and their variants, seeCollation Locales.

Collation and Views

  • You can specify a default collationfor a view at creation time. If no collation is specified, theview’s default collation is the “simple” binary comparisoncollator. That is, the view does not inherit the collection’sdefault collation.
  • String comparisons on the view use the view’s default collation.An operation that attempts to change or override a view’s defaultcollation will fail with an error.
  • If creating a view from another view, you cannot specify acollation that differs from the source view’s collation.
  • If performing an aggregation that involves multiple views, such aswith $lookup or $graphLookup, the views musthave the same collation.

Collation and Index Use

To use an index for string comparisons, an operation must alsospecify the same collation. That is, an index with a collationcannot support an operation that performs string comparisons on theindexed fields if the operation specifies a different collation.

For example, the collection myColl has an index on a stringfield category with the collation locale "fr".

  1. db.myColl.createIndex( { category: 1 }, { collation: { locale: "fr" } } )

The following query operation, which specifies the same collation asthe index, can use the index:

  1. db.myColl.find( { category: "cafe" } ).collation( { locale: "fr" } )

However, the following query operation, which by default uses the“simple” binary collator, cannot use the index:

  1. db.myColl.find( { category: "cafe" } )

For a compound index where the index prefix keys are not strings,arrays, and embedded documents, an operation that specifies adifferent collation can still use the index to support comparisonson the index prefix keys.

For example, the collection myColl has a compound index on thenumeric fields score and price and the string fieldcategory; the index is created with the collation locale"fr" for string comparisons:

  1. db.myColl.createIndex(
  2. { score: 1, price: 1, category: 1 },
  3. { collation: { locale: "fr" } } )

The following operations, which use "simple" binary collationfor string comparisons, can use the index:

  1. db.myColl.find( { score: 5 } ).sort( { price: 1 } )
  2. db.myColl.find( { score: 5, price: { $gt: NumberDecimal( "10" ) } } ).sort( { price: 1 } )

The following operation, which uses "simple" binary collationfor string comparisons on the indexed category field, can usethe index to fulfill only the score: 5 portion of the query:

  1. db.myColl.find( { score: 5, category: "cafe" } )

Collation and Unsupported Index Types

The following indexes only support simple binary comparison and donot support collation:

Tip

To create a text, a 2d, or a geoHaystack index on acollection that has a non-simple collation, you must explicitlyspecify {collation: {locale: "simple"} } when creating theindex.