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
/ /

$hash (aggregation expression)

New in version 8.3.

$hash

Generates and returns a binary hash value (BinData) from a UTF-8 string or binary data. Use $hash in an aggregation pipeline to compute binary hashes for storage, verification, or comparison. To get a hexadecimal string instead of binary data, use $hexHash.

$hash has the following syntax:

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

input

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

algorithm

String

Required. The hashing algorithm. Accepted values:

  • "md5"

  • "sha256"

  • "xxh64"

input Value
Result
Notes

UTF-8 string

Input must be a valid UTF-8 string.

null, undefined, or missing field

null

If input resolves to null or undefined, or refers to a missing field, $hash returns null.

If input resolves to a type other than a UTF-8 string or BinData, $hash returns an error.

If algorithm is not one of the accepted values, $hash 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 these documents:

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

The following example computes the SHA-256 hash of the filename field for each document:

db.files.aggregate( [
{
$project: {
filename: 1,
hash: {
$hash: {
input: "$filename",
algorithm: "sha256"
}
}
}
}
] )
[
{
_id: 1,
filename: 'report.pdf',
hash: Binary.createFromBase64('ZGbkUKFrd7hlxYKda2xW2fiSlWR1ZC2+uczENA/gGxU=', 0)
},
{
_id: 2,
filename: 'archive.zip',
hash: Binary.createFromBase64('jsO6p+AcJW/43CrXux9Tpmq+hHLmCKPmqJjcARAsmVA=', 0)
}
]

The following example hashes a literal string value:

db.aggregate( [
{ $documents: [ { val: "hello" } ] },
{
$project: {
_id: 0,
hash: {
$hash: {
input: "$val",
algorithm: "xxh64"
}
}
}
}
] )
[
{
hash: Binary.createFromBase64('JseCfYifbaM=', 0)
}
]

The following example computes the SHA-256 hash of a binary data field:

db.binaries.insertMany( [
{ _id: 1, data: new BinData(0, "aGVsbG8=") }
] )
db.binaries.aggregate( [
{
$project: {
hash: {
$hash: {
input: "$data",
algorithm: "sha256"
}
}
}
}
] )
[
{
_id: 1,
hash: Binary.createFromBase64('LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=', 0)
}
]

If input is null or refers to a missing field, $hash returns null:

db.aggregate( [
{
$documents: [
{ val: null },
{}
]
},
{
$project: {
hash: {
$hash: {
input: "$val",
algorithm: "sha256"
}
}
}
}
] )
[
{
hash: null
},
{
hash: null
}
]

Back

$gte

On this page