MongoCollection::findAndModify
(PECL mongo >=1.3.0)
MongoCollection::findAndModify — Update a document and return it
Описание
$query
[, array $update
[, array $fields
[, array $options
]]] )The findAndModify command atomically modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.
Список параметров
-
query
-
The query criteria to search for.
-
update
-
The update criteria.
-
fields
-
Optionally only return these fields.
-
options
-
An array of options to apply, such as remove the match document from the DB and return it.
Option Описание sort array Determines which document the operation will modify if the query selects multiple documents. findAndModify will modify the first document in the sort order specified by this argument. remove boolean Optional if update field exists. When TRUE
, removes the selected document. The default isFALSE
.update array Optional if remove field exists. Performs an update of the selected document. new boolean Optional. When TRUE
, returns the modified document rather than the original. The findAndModify method ignores the new option for remove operations. The default isFALSE
.upsert boolean Optional. Used in conjunction with the update field. When TRUE
, the findAndModify command creates a new document if the query returns no documents. The default is false. In MongoDB 2.2, the findAndModify command returnsNULL
when upsert isTRUE
.
Возвращаемые значения
Returns the original document, or the modified document when new is set.
Ошибки
Throws MongoResultException on failure.
Примеры
Пример #1 MongoCollection::findAndModify() example
<?php
$m = new Mongo;
$col = $m->selectDB("test")->jobs;
$col->insert(array(
"name" => "Next promo",
"inprogress" => false,
"priority" => 0,
"tasks" => array( "select product", "add inventory", "do placement"),
) );
$col->insert(array(
"name" => "Biz report",
"inprogress" => false,
"priority" => 1,
"tasks" => array( "run sales report", "email report" )
) );
$col->insert(array(
"name" => "Biz report",
"inprogress" => false,
"priority" => 2,
"tasks" => array( "run marketing report", "email report" )
),
array("w" => 1)
);
$retval = $col->findAndModify(
array("inprogress" => false, "name" => "Biz report"),
array('$set' => array('inprogress' => true, "started" => new MongoDate())),
null,
array(
"sort" => array("priority" => -1),
"new" => true,
)
);
var_dump($retval);
?>
Результатом выполнения данного примера будет что-то подобное:
array(6) { ["_id"]=> object(MongoId)#7 (1) { ["$id"]=> string(24) "5091b5b244415e8cc3000002" } ["inprogress"]=> bool(true) ["name"]=> string(10) "Biz report" ["priority"]=> int(2) ["started"]=> object(MongoDate)#8 (2) { ["sec"]=> int(1351726514) ["usec"]=> int(925000) } ["tasks"]=> array(2) { [0]=> string(20) "run marketing report" [1]=> string(12) "email report" } }
Пример #2 MongoCollection::findAndModify() error handling
<?php
$m = new Mongo;
$col = $m->selectDB("test")->jobs;
try {
$retval = $col->findAndModify(
array("inprogress" => false, "name" => "Next promo"),
array('$pop' => array("tasks" => -1)),
array("tasks" => array('$pop' => array("stuff"))),
array("new" => true)
);
} catch(MongoResultException $e) {
echo $e->getCode(), " : ", $e->getMessage(), "\n";
var_dump($e->getDocument());
}
?>
Результатом выполнения данного примера будет что-то подобное:
13097 : exception: Unsupported projection option: $pop array(3) { ["errmsg"]=> string(46) "exception: Unsupported projection option: $pop" ["code"]=> int(13097) ["ok"]=> float(0) }
Смотрите также
- The MongoDB » findAndModify command docs
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- MongoDB
- Базовые классы
- Функция MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
- Функция MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
- Функция MongoCollection::batchInsert() - Inserts multiple documents into this collection
- Функция MongoCollection::__construct() - Creates a new collection
- Функция MongoCollection::count() - Counts the number of documents in this collection
- Функция MongoCollection::createDBRef() - Creates a database reference
- Функция MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
- Функция MongoCollection::deleteIndex() - Deletes an index from this collection
- Функция MongoCollection::deleteIndexes() - Delete all indices for this collection
- Функция MongoCollection::distinct() - Retrieve a list of distinct values for the given key across a collection.
- Функция MongoCollection::drop() - Drops this collection
- Функция MongoCollection::ensureIndex() - Creates an index on the specified field(s) if it does not already exist.
- MongoCollection::find
- Функция MongoCollection::findAndModify() - Update a document and return it
- Функция MongoCollection::findOne() - Queries this collection, returning a single element
- Функция MongoCollection::__get() - Gets a collection
- Функция MongoCollection::getDBRef() - Fetches the document pointed to by a database reference
- Функция MongoCollection::getIndexInfo() - Returns information about indexes on this collection
- Функция MongoCollection::getName() - Returns this collection's name
- Функция MongoCollection::getReadPreference() - Get the read preference for this collection
- Функция MongoCollection::getSlaveOkay() - Get slaveOkay setting for this collection
- Функция MongoCollection::getWriteConcern() - Get the write concern for this collection
- Функция MongoCollection::group() - Performs an operation similar to SQL's GROUP BY command
- Функция MongoCollection::insert() - Inserts a document into the collection
- Функция MongoCollection::parallelCollectionScan() - Returns an array of cursors to iterator over a full collection in parallel
- Функция MongoCollection::remove() - Remove records from this collection
- Функция MongoCollection::save() - Saves a document to this collection
- Функция MongoCollection::setReadPreference() - Set the read preference for this collection
- Функция MongoCollection::setSlaveOkay() - Change slaveOkay setting for this collection
- Функция MongoCollection::setWriteConcern() - Set the write concern for this database
- Функция MongoCollection::toIndexString() - Converts keys specifying an index to its identifying string
- Функция MongoCollection::__toString() - String representation of this collection
- Функция MongoCollection::update() - Update records based on a given criteria
- Функция MongoCollection::validate() - Validates this collection
Коментарии
There is an easy way to find and replace by _id :
<?php
// ...
// Selecting unparsed lines
$cursor = $collection->find(array("mydata_isParsed" => array('$ne' => 1)));
// Doing our stuff
foreach($cursor as $document) {
// should always be ok, just in case
if (!isset($document["mydata_isParsed"])) {
// ... do some stuff
// flag as parsed and update line
$document["mydata_isParsed"] = 1;
$idField = '$id';
$collection->findAndModify(array("_id" => new MongoId($document["_id"]->$idField)), $document);
}
}