Sokil\Mongo\Cursor::copyToCollection PHP Method

copyToCollection() public method

Copy selected documents to another collection
public copyToCollection ( type $targetCollectionName, type $targetDatabaseName = null )
$targetCollectionName type
$targetDatabaseName type Target database name. If not specified - use current
    public function copyToCollection($targetCollectionName, $targetDatabaseName = null)
    {
        // target database
        if (!$targetDatabaseName) {
            $database = $this->collection->getDatabase();
        } else {
            $database = $this->client->getDatabase($targetDatabaseName);
        }
        // target collection
        $targetMongoCollection = $database->getCollection($targetCollectionName)->getMongoCollection();
        // cursor
        $cursor = $this->getCursor();
        $batchLimit = 100;
        $inProgress = true;
        // copy data
        while ($inProgress) {
            // get next pack of documents
            $documentList = array();
            for ($i = 0; $i < $batchLimit; $i++) {
                if (!$cursor->valid()) {
                    $inProgress = false;
                    if ($documentList) {
                        // still need batch insert
                        break;
                    } else {
                        // no documents to insert - just exit
                        break 2;
                    }
                }
                $documentList[] = $cursor->current();
                $cursor->next();
            }
            // insert
            $result = $targetMongoCollection->batchInsert($documentList);
            // check result
            if (is_array($result)) {
                if ($result['ok'] != 1) {
                    throw new Exception('Batch insert error: ' . $result['err']);
                }
            } elseif (!$result) {
                throw new Exception('Batch insert error');
            }
        }
        return $this;
    }