Definición
Nuevo en la versión 8.3.
Sintaxis
$hash tiene la siguiente sintaxis:
{ $hash: { input: <expression>, algorithm: <string> } }
Comportamiento
input Valor | Resultado | notas |
|---|---|---|
string UTF-8 | Input must be a valid UTF-8 string. | |
|
|
Si input se resuelve en null o indefinido, o se refiere a un campo ausente, $hash retorna null.
Si input se resuelve en un tipo diferente a una UTF-8 string o BinData, $hash devuelve un error.
Si algorithm no es uno de los valores aceptados, $hash devuelve un error.
Importante
MD5 no es un algoritmo criptográficamente seguro y no es adecuado para aplicaciones sensibles a la seguridad. Si estás aplicando hashing a información confidencial, usa "sha256" en su lugar.
MD5 también está deshabilitado en el modo FIPS. Si tu implementación se ejecuta con el modo FIPS habilitado, utiliza "sha256" o "xxh64" en su lugar.
Ejemplos
Los siguientes ejemplos usan una colección llamada files con estos document:
db.files.insertMany( [ { _id: 1, filename: "report.pdf" }, { _id: 2, filename: "archive.zip" } ] )
Hashear un valor de campo
El siguiente ejemplo calcula el hash SHA-256 del campo filename para cada 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) } ]
Hashea una string literal
El siguiente ejemplo realiza un hash de un valor de string literal:
db.aggregate( [ { $documents: [ { val: "hello" } ] }, { $project: { _id: 0, hash: { $hash: { input: "$val", algorithm: "xxh64" } } } } ] )
[ { hash: Binary.createFromBase64('JseCfYifbaM=', 0) } ]
BinData hash
El siguiente ejemplo calcula el hash SHA-256 de un campo de datos binary:
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
Si input es null o se refiere a un campo que falta, $hash devuelve null:
db.aggregate( [ { $documents: [ { val: null }, {} ] }, { $project: { hash: { $hash: { input: "$val", algorithm: "sha256" } } } } ] )
[ { hash: null }, { hash: null } ]