Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs 菜单
Docs 主页
/ /

$toHashedIndexKey(表达式操作符)

$toHashedIndexKey

使用 MongoDB 用于创建哈希索引的相同哈希函数计算并返回输入表达式的哈希值。 哈希函数将键或字符串映射到固定大小的数值。

注意

与哈希索引不同, $toHashedIndexKey聚合操作符考虑排序规则。 这意味着该操作符可以生成与基于相同数据的哈希索引的哈希值不匹配的哈希值。

$toHashedIndexKey 通过以下语法实现:

{ $toHashedIndexKey: <key or string to hash> }

您可以使用$toHashedIndexKey计算聚合管道中字符串的哈希值。 此示例计算字符串"string to hash"的哈希值:

db.aggregate(
[
{ $documents: [ { val: "string to hash" } ] },
{ $addFields: { hashedVal: { $toHashedIndexKey: "$val" } } }
]
)

示例输出:

[ { val: 'string to hash', hashedVal: Long("763543691661428748") } ]

有关聚合管道中的通用哈希,请参阅$hash$hexHash 。这些操作符与$toHashedIndexKey 的不同之处如下:

  • $hash$hexHash 是通用哈希表达式。当输入为null null或缺失时,表达式返回 。

  • $toHashedIndexKey 应用哈希索引语义。与 $hash$hexHash 不同,它将 null 和缺失值哈希为 Long 数值,而不是返回 null

要了解详情,请参阅:

后退

$toDouble

在此页面上