有条件地插入,更新或删除文档

时间:2016-06-12 23:44:27

标签: php mongodb

$document = $client->$db->$collection->findAndModify(
  [ $field => $value ], // query
  ['$set' => $updatedDocument], // update
  null, // only return these fields
  [
    "sort" => [], 
    "remove" => false, 
    "update" => [], // array for update? not sure what this does!
    "new" => false, 
    "upsert" => false 
  ]
);

使用syntax for the PHP Driver,是否可以在不向DB提出其他查询的情况下有条件地insertupdateremove文档?

例如:

$document = $client->$db->$collection->findAndModify(
  [ $field => $value ], // query
  // if $document != $newDocument: update
  ['$set' => $updatedDocument],
  null, // only return these fields
  [
    "sort" => [], 
    // if $document != $certainCondition: remove
    "remove" => true,
    "update" => [], 
    // if $document does not exist: insert (or upsert?)
    "new" => false,
    // if $document does not exist: upsert?
    "upsert" => false 
  ]
);

1 个答案:

答案 0 :(得分:2)

没有。 findAndModify只能更新或删除找到的文档。如果将remove标志设置为true并同时将更新字段设置为非空,则将找到,更新然后删除文档。无论你使用什么驱动程序,这都是mongodb的构建方式。

您必须使用普通更新并删除。