Doctrine\ODM\MongoDB\SchemaManager::ensureDocumentSharding PHP Method

ensureDocumentSharding() public method

Ensure sharding for collection by document name.
public ensureDocumentSharding ( string $documentName, array $indexOptions = [] )
$documentName string
$indexOptions array Options for `ensureIndex` command. It's performed on an existing collections.
    public function ensureDocumentSharding($documentName, array $indexOptions = array())
    {
        $class = $this->dm->getClassMetadata($documentName);
        if (!$class->isSharded()) {
            return;
        }
        $this->enableShardingForDbByDocumentName($documentName);
        $try = 0;
        do {
            $result = $this->runShardCollectionCommand($documentName);
            $done = true;
            // Need to check error message because MongoDB 3.0 does not return a code for this error
            if ($result['ok'] != 1 && strpos($result['errmsg'], 'please create an index that starts') !== false) {
                // The proposed key is not returned when using mongo-php-adapter with ext-mongodb.
                // See https://github.com/mongodb/mongo-php-driver/issues/296 for details
                if (isset($result['proposedKey'])) {
                    $key = $result['proposedKey'];
                } else {
                    $key = $this->dm->getClassMetadata($documentName)->getShardKey()['keys'];
                }
                $this->dm->getDocumentCollection($documentName)->ensureIndex($key, $indexOptions);
                $done = false;
                $try++;
            }
        } while (!$done && $try < 2);
        // Starting with MongoDB 3.2, this command returns code 20 when a collection is already sharded.
        // For older MongoDB versions, check the error message
        if ($result['ok'] == 1 || isset($result['code']) && $result['code'] == 20 || $result['errmsg'] == 'already sharded') {
            return;
        }
        throw MongoDBException::failedToEnsureDocumentSharding($documentName, $result['errmsg']);
    }

Usage Example

コード例 #1
0
ファイル: ShardCommand.php プロジェクト: alcaeus/mongodb-odm
 /**
  * @param SchemaManager $sm
  * @param object $document
  */
 protected function processDocumentIndex(SchemaManager $sm, $document)
 {
     $sm->ensureDocumentSharding($document);
 }