Definition
New in version 8.3.
Syntax
$hexHash has the following syntax:
{ $hexHash: { input: <expression>, algorithm: <string> } }
Field | Type | Description |
|---|---|---|
| Required. The value to hash. Must resolve to a valid
UTF-8 string or | |
| String | Required. The hashing algorithm. Accepted values:
|
Behavior
$hexHash returns an uppercase hexadecimal string. The length of
the output depends on the algorithm:
Algorithm | Output Length (characters) |
|---|---|
| 32 |
| 64 |
| 16 |
If input resolves to null or undefined, or refers to a
missing field, $hexHash returns null.
If input resolves to a type other than a UTF-8 string or
BinData, $hexHash returns an error.
If algorithm is not one of the accepted values, $hexHash
returns an error.
Important
MD5 is not a cryptographically secure algorithm and is not
suitable for security-sensitive applications. If you are
hashing sensitive data, use "sha256" instead.
MD5 is also disabled in FIPS mode. If your deployment runs
with FIPS mode enabled, use "sha256" or "xxh64"
instead.
Examples
The following examples use a collection named files with
this document:
db.files.insertMany( [ { _id: 1, filename: "report.pdf" } ] )
Hash a Field Value
The following example computes the SHA-256 hexadecimal hash of
the filename field:
db.files.aggregate( [ { $project: { filename: 1, hexHash: { $hexHash: { input: "$filename", algorithm: "sha256" } } } } ] )
[ { _id: 1, filename: 'report.pdf', hexHash: '6466E450A16B77B865C5829D6B6C56D9F892956475642DBEB9CCC4340FE01B15' } ]
The hexHash field contains the SHA-256 hash as a 64-character
uppercase hexadecimal string. To use a different algorithm, change
the algorithm value. For example, "xxh64" produces a
16-character string.
Null or Missing Input
If input is null, or input refers to a missing field,
$hexHash returns null:
db.aggregate( [ { $documents: [ { val: null }, {} ] }, { $project: { hexHash: { $hexHash: { input: "$val", algorithm: "sha256" } } } } ] )
[ { hexHash: null }, { hexHash: null } ]