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

$hash(聚合表达式)

8.3版本新增

$hash

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

$hash 通过以下语法实现:

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

input

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

algorithm

字符串

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

  • "md5"

  • "sha256"

  • "xxh64"

input
结果
注意

UTF-8 字符串

输入必须是有效的 UTF-8 字符串。

null、未定义或缺失字段

null

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

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

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

重要

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

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

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

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

以下示例计算每个文档的 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)
}
]

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

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

以下示例计算二进制数据字段的 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)
}
]

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

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

后退

$gte

在此页面上