Database Manual / Reference / Query Language / Expressions

$toHashedIndexKey (expression operator)(表达式运算符)

Definition定义

$toHashedIndexKey

Computes and returns the hash value of the input expression using the same hash function that MongoDB uses to create a hashed index. A hash function maps a key or string to a fixed-size numeric value.使用MongoDB用于创建哈希索引的相同哈希函数计算并返回输入表达式的哈希值。哈希函数将键或字符串映射到固定大小的数值。

Note

Unlike hashed indexes, the $toHashedIndexKey aggregation operator does not account for collation. This means the operator can produce a hash that does not match that of a hashed index based on the same data.与哈希索引不同,$toHashedIndexKey聚合运算符不考虑排序规则。这意味着运算符可以基于相同的数据生成与哈希索引不匹配的哈希。

Syntax语法

$toHashedIndexKey has the following syntax:具有以下语法:

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

Example示例

You can use $toHashedIndexKey to compute the hashed value of a string in an aggregation pipeline. This example computes the hashed value of the string "string to hash":您可以使用$toHashedIndexKey来计算聚合管道中字符串的哈希值。此示例计算字符串"string to hash"的哈希值:

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

Example output:示例输出:

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

Learn More了解更多