>>>>>>> cn
翻译或纠错本页面

片键索引

On this page

All sharded collections must have an index that starts with the shard key; i.e. the index can be an index on the shard key or a compound index where the shard key is a prefix of the index.

If you shard a collection without any documents and without such an index, the shardCollection command will create the index on the shard key. If the collection already has documents, you must create the index before using shardCollection.

重要

片键上的索引 不能多键索引.

Example

一个分片过的集合 peoplezipcode 为片键,且现在已经有了索引 { zipcode: 1 } ,按照如下步骤可以将此索引用 { zipcode: 1, username: 1 } 替换.

  1. 创建一个 { zipcode: 1, username: 1 } 的索引:

    db.people.createIndex( { zipcode: 1, username: 1 } );
    
  2. 当MongoDB创建这个新索引完成后,可以安全地删除 { zipcode: 1 } 索引:

    db.people.dropIndex( { zipcode: 1 } );
    

由于片键上的索引不能是多键索引,只有在 username 字段没有数组的情况下, { zipcode: 1, username: 1 } 才可以替换索引 { zipcode: 1 } .

如果你删除了对片键来说最后一个有效的索引,可以通过建立片键的索引进行恢复.

参见 Shard Key Limitations 以获得更多关于片键索引的限制.