|
| 1 | +======================= |
| 2 | +convertShardKeyToHashed |
| 3 | +======================= |
| 4 | + |
| 5 | +.. default-domain:: mongodb |
| 6 | + |
| 7 | +.. contents:: On this page |
| 8 | + :local: |
| 9 | + :backlinks: none |
| 10 | + :depth: 1 |
| 11 | + :class: singlecol |
| 12 | + |
| 13 | +Description |
| 14 | +----------- |
| 15 | + |
| 16 | +.. method:: convertShardKeyToHashed(<document>) |
| 17 | + |
| 18 | + Returns the hashed value for the input. The |
| 19 | + :method:`convertShardKeyToHashed()` method uses the same hashing |
| 20 | + function as the hashed index and can be used to see what the |
| 21 | + :doc:`hashed value </core/hashed-sharding>` would be for a key. |
| 22 | + |
| 23 | +Example |
| 24 | +------- |
| 25 | + |
| 26 | +Consider a sharded collection that uses a :doc:`hashed shard key |
| 27 | +</core/hashed-sharding>` [#populated]_ |
| 28 | + |
| 29 | +.. code-block:: javascript |
| 30 | + |
| 31 | + use test |
| 32 | + |
| 33 | + db.orders.createIndex( { _id: "hashed" } ) |
| 34 | + |
| 35 | + sh.shardCollection( "test.orders", { _id : "hashed" } ) |
| 36 | + |
| 37 | +If the following document exists in the collection, the hashed value of |
| 38 | +the ``_id`` field is used to distribute the document: |
| 39 | + |
| 40 | +.. code-block:: javascript |
| 41 | + |
| 42 | + { |
| 43 | + _id: ObjectId("5b2be413c06d924ab26ff9ca"), |
| 44 | + "item" : "Chocolates", |
| 45 | + "qty" : 25 |
| 46 | + } |
| 47 | + |
| 48 | + |
| 49 | +To determine the hashed value of ``_id`` field used to distribute the |
| 50 | +document across the shards, you can use the |
| 51 | +:method:`convertShardKeyToHashed` method: |
| 52 | + |
| 53 | +.. code-block:: javascrip |
| 54 | + |
| 55 | + convertShardKeyToHashed( { _id: ObjectId("5b2be413c06d924ab26ff9ca") } ) |
| 56 | + |
| 57 | +.. [#populated] |
| 58 | + |
| 59 | + If the collection already contains data, you must create a hashed |
| 60 | + index on the shard key before you shard the collection. For an empty |
| 61 | + collection, MongoDB creates the index as part of |
| 62 | + :method:`sh.shardCollection()`. |
| 63 | + |
0 commit comments