对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

$hash(聚合表达式)

8.3版本新增。

$hash

从 UTF-8 string 或 binary 数据生成并返回 binary 哈希值 (BinData)。在聚合管道中使用 $hash 来计算用于存储、验证或比较的 binary 哈希值。要获取十六进制字符串而不是binary数据,请使用$hexHash。

$hash 通过以下语法实现:

{ $hash: { input: <expression>, algorithm: <string> }}
字段
类型
说明

input

必需。要计算哈希值的值。必须解析为有效的 UTF-8 string 或 BinData。

algorithm

字符串

必需。哈希算法。接受的值:

  • "md5"

  • "sha256"

  • "xxh64"

input 值
结果
注意

UTF-8 字符串

input 必须是有效的 UTF-8 string。

null、未定义或缺失字段

null

如果 input 解析为 null 或未定义,或引用缺失字段,则 $hash 返回 null。

如果 input 解析为 UTF-8 string 或 BinData 以外的类型,$hash 将返回错误。

如果 algorithm 不是接受的值之一,$hash 将返回错误。

重要

MD5 不是一种加密安全算法,不适合安全敏感的应用程序。如果您要对敏感数据进行哈希处理,请改用 "sha256"。

MD5 在 FIPS模式下也会被禁用。如果您的部署在启用 FIPS模式的情况下运行,请改用 "sha256" 或 "xxh64"。

以下示例使用包含这些 document 的名为 files 的集合:

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

以下示例计算每个 document 的 filename字段的 SHA-256 哈希值:

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

以下示例对文字 string 值进行哈希处理:

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

以下示例计算 binary 数据字段的 SHA-256 哈希值:

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

如果 input 为 null 或指向缺失字段,则 $hash 返回 null:

db.aggregate( [ { $documents: [ { val: null }, {} ] }, { $project: { hash: { $hash: { input: "$val", algorithm: "sha256" } } } }] )
[ { hash: null }, { hash: null }]
给本页内容打分