In MongoDB Queryable Encryption, which query types can one encrypted field be configured for, and what must you fix when you create the collection?
answer
- declared up front, not later
- numbers and dates against strings
- only one pair may combine
- tags per value drive the cost
basics
~20 sA field takes equality or range, or for strings prefix, suffix or substring; only prefix and suffix combine. Query types, bounds and length limits are fixed at collection creation, and in 9.0 changing them means re-creating the collection.
solid answer
~40 sYou declare each field in `encryptedFields` with `path`, `bsonType` and optional `queries`; leaving out `queries` keeps it encrypted but unqueryable. `equality` serves `$eq`, `$ne`, `$in` and `$nin`. `range` adds `$lt`, `$lte`, `$gt` and `$gte` on `date`, `int`, `long`, `double` or `decimal`, with inclusive `min` and `max` that you should set tightly. On MongoDB 9.0, `prefix`, `suffix` and `substring` are GA for strings, queried through `$encStrStartsWith`, `$encStrEndsWith` and `$encStrContains`, each needing `strMinQueryLength`, `strMaxQueryLength`, `caseSensitive` and `diacriticSensitive`, plus `strMaxLength` for substring. Only `prefix` and `suffix` can share a field. These settings are immutable, so a new query type means a new collection. MongoDB 8.0 offers only equality and range.
code
javascript · 17 linesconst encryptedFieldsObject = {
fields: [
{ path: "cardToken", bsonType: "string",
queries: { queryType: "equality" } },
{ path: "dateOfBirth", bsonType: "date",
queries: { queryType: "range",
min: ISODate("1900-01-01"),
max: ISODate("2030-01-01") } },
{ path: "email", bsonType: "string",
queries: [
{ queryType: "prefix", strMinQueryLength: 3, strMaxQueryLength: 10,
caseSensitive: false, diacriticSensitive: false },
{ queryType: "suffix", strMinQueryLength: 3, strMaxQueryLength: 10,
caseSensitive: false, diacriticSensitive: false }
] }
]
}go deeper
Recall the five query types and that strings get prefix, suffix and substring while numbers and dates get range. Remember the choice is made before the collection exists.
Explain which BSON types each query type takes, why only prefix and suffix combine, and how min, max and the string length settings shape what a query may ask.
Size a configuration before creating it. Use the tag formulas, keep range bounds tight, prefer prefix or suffix to substring, and plan how you would re-create the collection if the query needs change.
Treat the encryption schema as an expensive long-lived contract. Require product owners to commit to query patterns up front, and weigh every enabled query type against write throughput, storage and its effect on leakage.
## How a field is declared **Queryable Encryption (QE)** is configured per collection through an **encryption schema**, the `encryptedFields` object you pass when you create the collection. Each entry names a `path`, a `bsonType` and optionally a `keyId` and `queries`. If `queries` is left out, the field is encrypted but cannot be queried. `_id` and its subfields cannot be encrypted. The server validates the schema when the collection is created. Each field is checked against the rules below, so a bad combination fails at that point rather than at the first query. ## The query types | Query type | BSON types | How you query it | Since | |---|---|---|---| | `equality` | Any supported type except `double`, `decimal`, `array`, `object` | `$eq`, `$ne`, `$in`, `$nin` | GA 7.0 | | `range` | `date`, `int`, `long`, `double`, `decimal` | The above plus `$lt`, `$lte`, `$gt`, `$gte` | 8.0 | | `prefix` | `string` | `$encStrStartsWith`, `$encStrNormalizedEq` | GA 9.0 | | `suffix` | `string` | `$encStrEndsWith`, `$encStrNormalizedEq` | GA 9.0 | | `substring` | `string` | `$encStrContains`, `$encStrNormalizedEq` | GA 9.0 | A range field answers equality too, by converting it to `$gte` and `$lte`, so `double` and `decimal` get equality through a range index. `$and`, `$or`, `$not`, `$nor`, `$expr` and `$exists` also work on an equality or range field. A comparison to `null` or a regular expression always throws an error. Two combination rules come straight from the server's validation: - A field may have at most two query types. - If it has two, they must be `prefix` and `suffix`. Equality with range and substring with anything else are both rejected. ## What you must settle at creation **Range fields** take `min` and `max`, which are inclusive and must match the field's type. They default to the limits of the BSON type, and querying outside them returns an error. Tighter bounds make queries cheaper. Advanced settings exist too: `sparsity` runs from 1 to 8 and defaults to 2, `trimFactor` defaults to 6, reduced where a small domain needs it, and `precision` applies to `double` and `decimal` only. **String fields** need `strMinQueryLength`, `strMaxQueryLength`, `caseSensitive` and `diacriticSensitive`, which server validation requires in 9.0 even though one manual page calls the two booleans optional. Substring also needs `strMaxLength`. For substring, the 9.0 server enforces a minimum query length of at least 2, a maximum query length of at most 6, and an `strMaxLength` of at most 50. Inserting a longer string fails in the client-side library, and querying outside the length bounds returns an error. **Contention** applies to all query types and defaults to 8 on the server's field configuration. Raising it helps inserts and updates on low-cardinality fields and slows finds. The important limit is that **the query type is immutable**. You cannot add one to a field, and changing which fields are encrypted or queryable means rebuilding the schema and re-creating the collection. QE works on new collections only. ## What each type costs Storage and write load follow the number of **tags** one value generates. Each write of a value adds two metadata documents per tag, one to the ESC and one to the ECOC. The manual's worst-case formulas are: 1. Equality: `T = 1`. 2. Prefix or suffix: `T = 1 + (strMaxQueryLength - strMinQueryLength + 1)`. 3. Substring: `T = 1 + (strMaxQueryLength - strMinQueryLength + 1) * (2 * strMaxLength + 2 - strMaxQueryLength - strMinQueryLength) / 2`. With a minimum of 2, a maximum of 6 and an `strMaxLength` of 50, substring reaches 236 tags per value. The manual therefore advises against substring on more than one field, and limits it to collections under 50 million documents and to cases where prefix and suffix fall short. ## A worked choice A payments service looks a customer up by card token and by a birth-date range: - `cardToken` is a string that is only ever matched whole, so it takes `equality`. - `dateOfBirth` is a `date` queried by interval, so it takes `range`, with bounds that span the real dates. - A field that is only read back, such as a note, needs no `queries` at all and writes no tags. ## Versions MongoDB 8.0 supports equality and range only. MongoDB 8.2 and 8.3 ran prefix, suffix and substring as a public preview using `prefixPreview`, `suffixPreview` and `substringPreview`. That preview is incompatible with the GA form, and 9.0 drivers cannot query fields encrypted for it, so moving means loading the data into a new collection. To use the string query types through `mongosh`, you also need `crypt_shared` 9.0 or later, passed with `--cryptSharedLibPath`.
- Why can't a field be configured for both equality and range?The server's validation allows two query types on a field only when they are `prefix` and `suffix`. It does not need both, though: a `range` field also answers equality, by converting it to `$gte` and `$lte`. So a field needing both is configured as `range` alone.
- What happens when a value is longer than strMaxLength on a substring field?The write fails on the client. `libmongocrypt` rejects the string during encoding because it is longer than the maximum length for substring indexing, measured in code points. The server's option description still says such a string is simply not indexed, but the encoding code raises an error.
- How do you move a MongoDB 8.2 preview substring field to 9.0?Upgrade the server and drivers, then create a new collection using `substring` and load the data. If there is no plaintext copy, read the documents through a 9.0 driver, which can still decrypt preview data, filtering on an unencrypted field or scanning, because it cannot query the preview-encrypted fields. `mongodump` and `mongoexport` do not decrypt.
- You can add range queries to an existing encrypted field with a collMod later.
- A field needing both equality and range is configured with both query types.
- Queryable Encryption string searches use $regex, which the driver encrypts for you.
- MongoDB 8.0 runs prefix and substring queries the same way MongoDB 9.0 does.
- Substring costs about the same as prefix because both index a string field.
Assumes MongoDB 9.0, where prefix, suffix and substring queries are GA; MongoDB 8.0 offers equality and range only.