MongoCollection::findAndModify PHP Method

findAndModify() public method

Update a document and return it
public findAndModify ( array $query, array $update = null, array $fields = null, array $options = [] ) : array
$query array The query criteria to search for.
$update array The update criteria.
$fields array Optionally only return these fields.
$options array An array of options to apply, such as remove the match document from the DB and return it.
return array Returns the original document, or the modified document when new is set.
    public function findAndModify(array $query, array $update = null, array $fields = null, array $options = [])
    {
        $query = TypeConverter::fromLegacy($query);
        try {
            if (isset($options['remove'])) {
                unset($options['remove']);
                $document = $this->collection->findOneAndDelete($query, $options);
            } else {
                $update = is_array($update) ? $update : [];
                if (isset($options['update']) && is_array($options['update'])) {
                    $update = $options['update'];
                    unset($options['update']);
                }
                $update = TypeConverter::fromLegacy($update);
                if (isset($options['new'])) {
                    $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
                    unset($options['new']);
                }
                $options['projection'] = is_array($fields) ? TypeConverter::fromLegacy($fields) : [];
                if (!\MongoDB\is_first_key_operator($update)) {
                    $document = $this->collection->findOneAndReplace($query, $update, $options);
                } else {
                    $document = $this->collection->findOneAndUpdate($query, $update, $options);
                }
            }
        } catch (\MongoDB\Driver\Exception\ConnectionException $e) {
            throw new MongoResultException($e->getMessage(), $e->getCode(), $e);
        } catch (\MongoDB\Driver\Exception\Exception $e) {
            throw ExceptionConverter::toLegacy($e, 'MongoResultException');
        }
        if ($document) {
            $document = TypeConverter::toLegacy($document);
        }
        return $document;
    }

Usage Example

Beispiel #1
0
 /**
  * Lookup a specific cache entry
  * 
  * Optionally, increment the hit counter when loading the cache entry
  * 
  * @param integer $id
  * @param boolean $incrementHitCounter = false
  * @return array | FALSE
  */
 private function get($id, $incrementHitCounter = false)
 {
     if ($incrementHitCounter === true) {
         return $this->_collection->findAndModify(array('_id' => $id), array('$inc' => array('hits' => 1)));
     } else {
         return $this->_collection->findOne(array('_id' => $id));
     }
 }
All Usage Examples Of MongoCollection::findAndModify