Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

$hexHash (aggregation expression)

New in version 8.3.

$hexHash

Generates and returns an uppercase hexadecimal string representation of a hash value from a UTF-8 string or binary data (BinData). To get binary data instead of a hexadecimal string, use $hash.

$hexHash has the following syntax:

{
$hexHash: {
input: <expression>,
algorithm: <string>
}
}
Field
Type
Description

input

Required. The value to hash. Must resolve to a valid UTF-8 string or BinData.

algorithm

String

Required. The hashing algorithm. Accepted values:

  • "md5"

  • "sha256"

  • "xxh64"

$hexHash returns an uppercase hexadecimal string. The length of the output depends on the algorithm:

Algorithm
Output Length (characters)

"md5"

32

"sha256"

64

"xxh64"

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.

The following examples use a collection named files with this document:

db.files.insertMany( [
{ _id: 1, filename: "report.pdf" }
] )

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.

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
}
]

Back

$hash

On this page