Collation in Azure DocumentDB

Collation lets you choose how Azure DocumentDB compares and sorts strings. Without collation, string comparisons are binary and case-sensitive.

Use collation to:

  • Match names such as Ada, ADA, and ada regardless of capitalization.
  • Choose whether accented values such as cafe and café compare as equivalent.
  • Apply language-specific comparison rules for languages such as English, French, and Turkish.
  • Sort numbers within strings numerically—for example, item1, item2, and item10.
  • Enforce case-insensitive uniqueness through collated unique indexes on unsharded collections.

Collation changes how values are compared, not the values stored in your documents.

If collation is already enabled on your cluster, start with a query.

Enable collation on Azure DocumentDB

Enable the preview on your cluster by using Azure portal, Azure CLI, or Bicep. Enablement doesn't change existing collection defaults, indexes, or stored data.

You need permission to update the cluster resource.

Important

Collation is available in preview. Enabling Collation is irreversible: retain it in every subsequent previewFeatures list. Supplied lists replace the entire list, so preserve all existing features. Review the current limitations before using the preview in your application.

If the primary has existing replica clusters, enable Collation separately on every replica first. Wait for each replica's configuration update to complete before enabling it on the primary. Replicas created after primary enablement inherit the feature and its configuration.

Enable collation through Azure portal

Enable the feature from your cluster's Features page.

  1. Sign in to the Azure portal.
  2. Open your Azure DocumentDB cluster.
  3. Under Settings, select Features.
  4. Select Collation.
  5. Review the irreversible-enablement and replica requirements, and then select OK.
  6. Wait for the configuration update to complete, and then refresh Features to verify that collation is enabled.

Enable collation using Azure CLI

The following example uses Bash and jq, which are available in Azure Cloud Shell. For CLI setup and command details, see Related content.

Enable collation on an existing cluster with az documentdb mongocluster update. First, read the current preview features, add Collation, and preserve every existing feature.

Replace the resource ID with the ID of the replica or primary you're updating.

set -euo pipefail

resourceId="/subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.DocumentDB/mongoClusters/<cluster-name>"

previewFeatures="$(az documentdb mongocluster show \
  --ids "$resourceId" \
  --query properties.previewFeatures \
  --output json)"

previewFeatures="$(printf '%s' "${previewFeatures:-null}" | jq \
  '((. // []) + ["Collation"] | unique)')"

az documentdb mongocluster update \
  --ids "$resourceId" \
  --preview-features "$previewFeatures"

Verify the configuration with az documentdb mongocluster show.

az documentdb mongocluster show \
  --ids "$resourceId" \
  --query 'properties.{features:previewFeatures,state:provisioningState,status:clusterStatus}' \
  --output json

Check that features contains Collation, state is Succeeded, and status is Ready. Wait for configuration updates to finish before sending collation requests. The feature can appear in resource metadata before its backend configuration is applied. Complete this verification on each existing replica before enabling the primary.

Enable collation using Bicep

In the Bicep template that already manages your cluster, include Collation in properties.previewFeatures. Supply the complete list of other enabled preview features as existingPreviewFeatures; use an empty array only when there are none.

The following excerpt shows the property in context. Merge it into your existing resource declaration and retain its other properties, identity, and tags. Don't deploy this excerpt as a standalone replacement configuration.

param clusterName string
param location string
param existingPreviewFeatures array

resource cluster 'Microsoft.DocumentDB/mongoClusters@2026-06-15-preview' = {
  name: clusterName
  location: location
  properties: {
    // Retain the other properties from your existing cluster declaration.
    previewFeatures: union(existingPreviewFeatures, [
      'Collation'
    ])
  }
}

Deploy your complete template through your normal deployment process and verify the resulting preview-feature list as shown in the CLI example. For existing replicas, complete enablement and verification on every replica before deploying the primary's change.

See the resource template reference for the resource shape and previewFeatures property.

Get started with collation

Connect to your cluster by using the DocumentDB extension for Visual Studio Code. Then open the extension's interactive shell and select an empty database reserved for testing.

The account that you use must have permission to create collections and indexes, and to read and write documents. Run the examples in the order in which they appear. Subsequent sections reuse the collationContacts collection created in this section, and each sample collection is created only once.

Create the sample collection:

db.createCollection("collationContacts");

db.collationContacts.insertMany([
  { _id: 1, name: "Ada", label: "item2" },
  { _id: 2, name: "ADA", label: "item10" },
  { _id: 3, name: "Grace", label: "item1" }
]);

Without collation, searching for ada returns no matches because binary comparison distinguishes uppercase and lowercase letters:

db.collationContacts.find({ name: "ada" });

To match both Ada and ADA, use English collation with strength: 2, which ignores case while preserving accent differences:

db.collationContacts
  .find({ name: "ada" }, { _id: 1, name: 1 })
  .collation({ locale: "en", strength: 2 })
  .sort({ _id: 1 });

Expected result:

[
  { "_id": 1, "name": "Ada" },
  { "_id": 2, "name": "ADA" }
]

Both documents now match. Their stored names remain unchanged. Field names remain case-sensitive.

To use binary, case-sensitive comparison, specify { locale: "simple" } without additional collation options. An explicit simple collation also overrides a collection default for a single operation.

db.collationContacts
  .find({ name: "Ada" }, { _id: 1, name: 1 })
  .collation({ locale: "simple" });

Only document 1, which contains the exact value Ada, matches.

Configure collation

Choose where collation rules apply, and then choose the options that define those rules.

Collation configuration levels

Configuration What it controls When to use
Operation Sets the comparison rules for one supported operation. It overrides the collection default for that operation. Only certain queries need different comparison rules, or you want to evaluate behavior before choosing a default.
Collection Sets the default rules when you create a new, unsharded collection. Supported operations and indexes inherit the default unless they explicitly specify their own collation. Most operations on a collection should use the same comparison rules.
Index Sets the comparison rules for indexed string values and unique-key checks. It doesn't determine the collation that a query uses. You need to support collation-sensitive queries or sorting, or to enforce case-insensitive uniqueness.

A query's effective collation comes from the operation or, if the operation doesn't specify one, from the collection default. For collation-sensitive comparisons or sorting to use an index, the index collation must match that effective collation. Azure DocumentDB doesn't choose a query's collation based on available indexes. For details, see Use collation with indexes.

Start with operation-level collation to evaluate application behavior before choosing a collection-wide default.

Collation options

Specify the locale and the options you want to customize. Omitted options use the selected locale's defaults.

Option Accepted values Description
locale A supported locale identifier, or "simple". Required. Selects language-specific comparison rules. Use "simple" without other options for binary comparison.
strength Integers from 1 to 5. Sets the comparison level. See Comparison strength.
caseLevel true or false. When true, adds case comparison at strengths 1 and 2.
caseFirst "off", "upper", or "lower". Controls whether uppercase or lowercase sorts first when case is compared. "off" uses the locale's case ordering; it doesn't make comparisons case-insensitive.
numericOrdering true or false. When true, compares digit sequences within strings by numeric value.
alternate "non-ignorable" or "shifted". "non-ignorable" compares spaces and punctuation like other characters. "shifted" ignores the characters selected by maxVariable at strengths 1 through 3.
maxVariable "punct" or "space". Applies with alternate: "shifted". "punct" selects spaces and punctuation; "space" selects only spaces.
backwards true or false. When true, compares secondary (accent) differences from the end of the string.
normalization true or false. When true, checks whether text requires Unicode normalization before comparison. It doesn't change stored data.

For example, the following collation specification uses US English rules, ignores case, and compares digit sequences numerically:

{
  "locale": "en_US",
  "strength": 2,
  "numericOrdering": true
}

Locale identifiers are case-sensitive and regional variants are limited. For example, use en_US, not en-US. Don't assume every language tag is accepted. The system rejects unsupported locales, unknown options, and invalid option types.

Comparison strength

The strength option determines which differences to consider during string comparisons. The following descriptions apply to English with the other options at their defaults. Other locales and options can change the results.

Strength Level Differences considered
1 Primary. Base letters only. Case and accents are ignored.
2 Secondary. Base letters and accents. Case is ignored.
3 Tertiary. Base letters, accents, and case. This level is the default.
4 Quaternary. Adds a level for differences that are otherwise equal, such as punctuation that alternate: "shifted" ignores at strengths 1 through 3.
5 Identical. Adds a final tie-breaking level for strings that are equal at all other levels. It isn't a substitute for binary simple comparison.

To ignore accents but distinguish case, combine strength 1 with caseLevel: true. To ignore spaces and punctuation, use alternate: "shifted" with a strength from 1 to 3. The following scenarios demonstrate both combinations.

Common collation scenarios

Each scenario shows how collation changes string comparisons without changing stored values. Run each collection's setup commands before its queries. The numeric-sorting and regular-expression examples reuse collationContacts from Get started with collation.

Compare strings with accents

Create three variants of a word to see how comparison strength affects matching.

db.createCollection("collationCafe");
db.collationCafe.insertMany([
  { _id: 1, name: "cafe" },
  { _id: 2, name: "CAF\u00c9" },
  { _id: 3, name: "caf\u00e9" }
]);

db.collationCafe.countDocuments(
  { name: "caf\u00e9" },
  { collation: { locale: "en", strength: 1 } }
);
db.collationCafe.countDocuments(
  { name: "caf\u00e9" },
  { collation: { locale: "en", strength: 2 } }
);
db.collationCafe.countDocuments(
  { name: "caf\u00e9" },
  { collation: { locale: "en", strength: 3 } }
);
Strength Matching document IDs Behavior for English with other default options
1 1, 2, 3. Ignores case and accents.
2 2, 3. Distinguishes accents but ignores case.
3 3. Distinguishes both case and accents.

To ignore accents while distinguishing case, use caseLevel: true with strength 1:

db.collationCafe.countDocuments(
  { name: "caf\u00e9" },
  { collation: { locale: "en", strength: 1, caseLevel: true } }
);

The result is 2 (documents 1 and 3).

Apply language-specific comparisons

Case comparison depends on locale. Turkish distinguishes dotted and dotless i.

db.createCollection("collationTurkishNames");
db.collationTurkishNames.insertMany([
  { _id: 1, name: "\u0130pek" },
  { _id: 2, name: "ipek" },
  { _id: 3, name: "Ipek" },
  { _id: 4, name: "\u0131pek" }
]);

db.collationTurkishNames
  .find({ name: "ipek" }, { _id: 1 })
  .collation({ locale: "tr", strength: 2 })
  .sort({ _id: 1 });

Documents 1 and 2 match. With the same collation, filtering on Ipek matches documents 3 and 4.

Ignore spaces and punctuation

Use shifted comparison rules when spacing and punctuation shouldn't distinguish product codes.

db.createCollection("collationProductCodes");
db.collationProductCodes.insertMany([
  { _id: 1, code: "AB-12" },
  { _id: 2, code: "AB 12" },
  { _id: 3, code: "AB12" }
]);

db.collationProductCodes
  .find({ code: "AB12" }, { _id: 1 })
  .collation({
    locale: "en",
    strength: 3,
    alternate: "shifted",
    maxVariable: "punct"
  })
  .sort({ _id: 1 });

All three documents match. With the default alternate: "non-ignorable", only document 3 matches this filter.

Sort strings containing numbers

By default, strings are sorted lexicographically, so item10 comes before item2. Set numericOrdering: true to compare digit sequences by their numeric value:

db.collationContacts
  .find({}, { _id: 0, label: 1 })
  .collation({ locale: "en", numericOrdering: true })
  .sort({ label: 1 });

Expected result:

[
  { "label": "item1" },
  { "label": "item2" },
  { "label": "item10" }
]

The values remain strings; this option changes only how you compare them.

Keep regular-expression matching separate

Regular-expression matching doesn't use collation comparison rules.

db.collationContacts.countDocuments(
  { name: { $regex: "^ada$" } },
  { collation: { locale: "en", strength: 2 } }
);

db.collationContacts.countDocuments(
  { name: { $regex: "^ada$", $options: "i" } },
  { collation: { locale: "simple" } }
);

The first count is 0; the second is 2. The regex option i provides case-insensitive regex matching, not the full language-aware behavior of collation.

Use collation with database operations

The preview supports collation in the following operations, subject to the current limitations.

Operation Supported behavior
find Collation-aware filtering, comparison expressions, projections, and sorting.
count and distinct Collation-aware filtering; distinct also deduplicates equivalent values.
aggregate Supported stages and expressions, including $match, $sort, $group, and supported accumulators.
update, delete, and findAndModify Collation-aware document selection and supported comparison-sensitive update effects.
Collection creation Default collation for a new, unsharded collection.
Index creation Collation on supported indexes; collated unique indexes on unsharded collections.

Set a collection default

Specify a default collation when creating an unsharded collection:

db.createCollection("collatedContacts", {
  collation: { locale: "en", strength: 2 }
});

db.collatedContacts.insertMany([
  { _id: 1, name: "Ada" },
  { _id: 2, name: "ADA" }
]);

db.collatedContacts.find({ name: "ada" });

Both documents match because the query inherits the collection default. Override the default for a single operation:

db.collatedContacts
  .find({ name: "Ada" })
  .collation({ locale: "simple" });

Only document 1 matches. An operation-level override is a complete collation specification, not a merge with the collection default.

Important

You can't modify a collection's default collation after creation. To use a different default, create a new collection and migrate the data. A non-simple collection default also applies to _id uniqueness: under English strength 2, string _id values Ada and ADA are equivalent.

Count and deduplicate matching values

Reuse collationContacts from Get started with collation.

db.collationContacts.countDocuments(
  { name: "ada" },
  { collation: { locale: "en", strength: 2 } }
);

db.collationContacts.distinct(
  "name",
  {},
  { collation: { locale: "en", strength: 2 } }
);

The count is 2. The distinct result contains Grace and one representative of the Ada/ADA equivalence class. Don't depend on the representative spelling or value order.

Group equivalent values in aggregation

Group the names in collationContacts:

db.collationContacts.aggregate(
  [
    { $group: { _id: "$name", contacts: { $sum: 1 } } },
    { $sort: { contacts: -1 } }
  ],
  { collation: { locale: "en", strength: 2 } }
);

The two Ada spellings form one group with count 2; Grace forms a group with count 1. For an example that collects distinct string values with a comparison-sensitive accumulator, create an orders collection:

db.createCollection("collationOrders");
db.collationOrders.insertMany([
  { _id: 1, customer: "Ada", city: "Paris", amount: 10 },
  { _id: 2, customer: "ADA", city: "PARIS", amount: 30 },
  { _id: 3, customer: "Grace", city: "Lyon", amount: 20 },
  { _id: 4, customer: "GRACE", city: "LYON", amount: 40 }
]);

db.collationOrders.aggregate(
  [
    {
      $group: {
        _id: "$customer",
        orders: { $sum: 1 },
        total: { $sum: "$amount" },
        average: { $avg: "$amount" },
        minimum: { $min: "$amount" },
        maximum: { $max: "$amount" },
        cities: { $addToSet: "$city" }
      }
    },
    { $sort: { total: 1 } }
  ],
  { collation: { locale: "en", strength: 2 } }
);
Customer equivalence class Orders Total Average Minimum Maximum Distinct cities
Ada / ADA 2 40 20 10 30 1
Grace / GRACE 2 60 30 20 40 1

The representative casing of _id and the retained city value aren't guaranteed. $addToSet doesn't guarantee array order. One effective collation applies to the pipeline, including supported nested pipelines.

Update and delete matching documents

Use a separate collection so these writes don't change the earlier query examples.

db.createCollection("collationWriteContacts");
db.collationWriteContacts.insertMany([
  { _id: 1, name: "Ada", status: "pending", visits: 0 },
  { _id: 2, name: "ADA", status: "pending", visits: 0 },
  { _id: 3, name: "Grace", status: "pending", visits: 0 }
]);

db.collationWriteContacts.updateMany(
  { name: "ada" },
  { $set: { status: "reviewed" } },
  { collation: { locale: "en", strength: 2 } }
);

The update reports matchedCount: 2 and modifiedCount: 2.

db.collationWriteContacts.findOneAndUpdate(
  { name: "grace" },
  { $inc: { visits: 1 } },
  {
    collation: { locale: "en", strength: 2 },
    returnDocument: "after"
  }
);

db.collationWriteContacts.deleteMany(
  { name: "ada" },
  { collation: { locale: "en", strength: 2 } }
);

The update returns Grace with visits: 1; the delete removes the two Ada documents (deletedCount: 2).

Specify collation for each batch entry

In raw update and delete commands, specify collation inside each operation entry, not as a top-level batch option.

db.createCollection("collationBatchContacts");
db.collationBatchContacts.insertMany([
  { _id: 1, name: "Ada", status: "pending" },
  { _id: 2, name: "ADA", status: "pending" },
  { _id: 3, name: "Grace", status: "pending" }
]);

db.runCommand({
  update: "collationBatchContacts",
  updates: [
    {
      q: { name: "ada" },
      u: { $set: { status: "reviewed" } },
      multi: true,
      collation: { locale: "en", strength: 2 }
    },
    {
      q: { name: "Grace" },
      u: { $set: { status: "reviewed" } },
      multi: false,
      collation: { locale: "simple" }
    }
  ]
});

The command reports n: 3 and nModified: 3. insert doesn't accept an operation-level collation; inserts still enforce collection validation and index uniqueness rules.

Plan for sharded writes

With non-simple collation, a collation-sensitive string shard key predicate might not target a single shard.

Operation Routing requirement
updateOne with upsert: false, and deleteOne Can use exact _id equality when the shard key predicate can't target one shard. _id lookup honors collation, including string identifiers.
updateOne with upsert: true, and findAndModify Require an exact shard key match that can target one shard without collation-sensitive string routing. No _id fallback applies unless _id also supplies the required shard key match.

Validate your shard key predicates and operation behavior before using collation-sensitive writes in sharded workloads.

Use collation with indexes

For collation-sensitive string predicates and index-provided ordering, the index must match the effective query collation, including locale and comparison options. A matching index is eligible, but selection isn't guaranteed; supported queries can still scan and apply collation.

Create an explicitly collated index

Create an index on collationContacts from Get started with collation:

db.collationContacts.createIndex(
  { name: 1 },
  {
    name: "name_en_case_insensitive",
    collation: { locale: "en", strength: 2 }
  }
);

An English strength-2 index doesn't provide strength-3 string comparison. A hint can't make incompatible collations equivalent.

Combine inherited and binary indexes

The collatedContacts collection from Set a collection default has an English strength-2 default. Create one index that inherits the default and one binary index.

db.collatedContacts.createIndex(
  { name: 1 },
  {
    name: "name_inherited"
  }
);

db.collatedContacts.createIndex(
  { name: 1 },
  {
    name: "name_binary",
    collation: { locale: "simple" }
  }
);

db.collatedContacts
  .find({ name: "Ada" }, { _id: 1, name: 1 })
  .collation({ locale: "simple" })
  .hint("name_binary");

Only document 1 matches. The index doesn't change the query's effective collation; the explicit operation override does.

Enforce case-insensitive uniqueness

Collated unique indexes are supported only on unsharded collections in this preview.

db.createCollection("collationUniqueContacts");
db.collationUniqueContacts.createIndex(
  { name: 1 },
  {
    name: "unique_name_en",
    unique: true,
    collation: { locale: "en", strength: 2 }
  }
);

db.collationUniqueContacts.insertOne({ _id: 1, name: "Ada" });

The following insert fails with duplicate-key error 11000 because Ada and ADA compare as equivalent under the index collation:

db.collationUniqueContacts.insertOne({ _id: 2, name: "ADA" });

Resolve collation-equivalent existing values before building a unique index. An operation-level override can't relax uniqueness constraints.

Inspect collection and index metadata

Inspect the collection created in Set a collection default and the index created in Create an explicitly collated index:

db.getCollectionInfos({ name: "collatedContacts" }).map(info => ({
  name: info.name,
  collation: info.options.collation
}));

db.collationContacts.getIndexes();

getCollectionInfos() shows a collection's default in options.collation. getIndexes() lists every index on the collection, and collated indexes include a collation field—for example, name_en_case_insensitive shows { locale: "en", strength: 2 }. Compare complete collation options when diagnosing index eligibility.

Limitations

Review the limitations before adopting the preview, particularly for sharded operations, index types, and aggregation support.

Query and index restrictions refer to non-simple collation unless stated otherwise.

  • Feature lifecycle: Enabling Collation is irreversible. Retain the feature in every subsequent previewFeatures replacement list. Enable existing replicas and wait for their configuration updates to complete before enabling the primary.
  • Collection defaults: You can set a non-simple default only on a new, unsharded collection. You can't change an existing collection's default in place.
  • Sharding: You can't shard, reshard, or unshard a collection with a non-simple default. Operation-level collation on sharded collections is separate from collection-default support.
  • Sharded single-document writes: Some writes require an exact shard key route that doesn't depend on collation-sensitive string comparison. Not every operation permits an _id fallback. See sharded write routing.
  • Unique indexes: Collated unique indexes are supported only on unsharded collections. An operation override doesn't change an index's uniqueness rules. Collection-default collation also applies to _id uniqueness.
  • Aggregation stages: Non-simple collation isn't supported with $bucket, $bucketAuto, $sortByCount, $setWindowFields, $geoNear, $fill, $densify, or $merge, including when inherited from a collection default.
  • $group accumulators: $group is supported with non-simple collation, including $sum, $avg, $min, $max, $count, and $addToSet. Unsupported cases include $push, $mergeObjects, N-valued accumulators, and $top/$bottom. Some sorted $first/$last pipelines are also unsupported.
  • Variable initializers: Command-level let initializers in find, aggregate, delete, and findAndModify with remove: true, and $lookup let initializers, use binary comparison. Supported comparisons using $$variables, including in a $let in expression, can still use the effective collation.
  • Views: Declaring a view collation, or creating or modifying a view that references a collection with a non-simple default, isn't supported.
  • Index types: Text, hashed, geospatial, and vector indexes don't support non-simple collation, and neither do wildcard indexes that use wildcardProjection. Search indexes can't be created on collections with a non-simple default.
  • Long indexed values: Collated indexes don't truncate long strings, embedded documents, or nested arrays. Writes, index builds, and indexed queries fail when one of these values is larger than about 2.6 KB. In a compound index, each key field gets an equal share of that limit.

Don't depend on the representative spelling of a grouped or distinct equivalence class, or on $addToSet array order. When a sort considers multiple strings equal, add a unique, collation-insensitive tie-breaker, such as a numeric _id, if you need deterministic ordering.