Definition
New in version 8.3.
Syntax
$hash has the following syntax:
{ $hash: { input: <expression>, algorithm: <string> } }
Field | Type | Description |
|---|---|---|
| Required. The value to calculate the hash for. Must resolve to a
valid UTF-8 string or | |
| String | Required. The hashing algorithm. Accepted values:
|
Behavior
input Value | Result | Notes |
|---|---|---|
UTF-8 string | Input must be a valid UTF-8 string. | |
|
|
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.
Examples
The following examples use a collection named files with
these documents:
db.files.insertMany( [ { _id: 1, filename: "report.pdf" }, { _id: 2, filename: "archive.zip" } ] )
Hash a Field Value
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) } ]
Hash a Literal String
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) } ]
Hash BinData
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) } ]
Null or Missing Input
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 } ]