> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# $toHashedIndexKey (expression operator)

## Definition

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.

**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.

## Syntax

`$toHashedIndexKey` has the following syntax:

```javascript
{ $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"`:

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

Example output:

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

## Learn More

For general-purpose hashing in an aggregation pipeline, see [`$hash`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/hash.md#mongodb-expression-exp.-hash) and [`$hexHash`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/hexhash.md#mongodb-expression-exp.-hexHash). These operators differ from `$toHashedIndexKey` as follows:

- [`$hash`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/hash.md#mongodb-expression-exp.-hash) and [`$hexHash`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/hexhash.md#mongodb-expression-exp.-hexHash) are general-purpose hashing expressions. The expressions return `null` when the input is `null` or missing.

- `$toHashedIndexKey` applies hashed index semantics. Unlike `$hash` and `$hexHash`, it hashes `null` and missing values to a `Long` numeric value rather than returning `null`.

To learn more, see:

- [`$hash`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/hash.md#mongodb-expression-exp.-hash)

- [`$hexHash`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/hexhash.md#mongodb-expression-exp.-hexHash)

- [`convertShardKeyToHashed()`](https://www.mongodb.com/docs/manual/reference/method/convertshardkeytohashed.md#mongodb-method-convertShardKeyToHashed)
