How to use findAndModify in php and mongodb

2020-06-28 01:50发布

问题:

I want to increment id by 1 but I there is a problem while running the php page The Error is

Fatal error: Call to undefined method MongoCollection::findAndModify() in C:\wamp\www\....

My Code is:

<?php
 // connect
 $m = new Mongo();
 $db=$m->demo;//selecting database named demo
 $db->authenticate("abc","abc");//authenticate database by its username and  password
 $next =nextValue($db);
 $db->counters.insert(array("_id"=>$next, "name"=>'B'));
 print_r($db->runcommand(array('getlasterror'=>1,'fsync'=>true)));
 function nextValue($db)
 {
      //$next =$db->counters->findAndModify(array('query'=> array("_id"=> "total"),'update'=>array($inc=> array("total"=> 1))));
      //I Used above Code Before this code
      $next =$db->command(array('findAndModify'=>'counters'),array('query'=> array("_id"=> "total"),'update'=>array($inc=> array("total"=> 1))));
      if($next['total']==0)
      {
         $db->counters->insert(array("_id"=> "total", "name" => 'A'));
         $next =$db->counters->findAndModify(array('query'=> array("_id"=> "total"),'update'=>array($inc=> array("total"=> 1))));
      }
      return $next['total'];
 }
?>

回答1:

There is no findAndModify function yet. Instead of findAndModify, you'll have to run a generic database command to do this:

$db->command(
  array(
    "findandmodify" => "counters",
    "query" => array("_id"=> "total"),
    "update" => array($inc=> array("total"=> 1)),
  )
);

There is an open issue at https://jira.mongodb.org/browse/PHP-117 to implement findAndModify though.



回答2:

Use findAndUpdate();

$collection = (new MongoDB\Client)->test->restaurants;

$updatedRestaurant = $collection->findOneAndUpdate(
    [ 'restaurant_id' => '40361708' ],
    [ '$set' => [ 'address.building' => '761' ]],
    [
        'projection' => [ 'address' => 1 ],
        'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
    ]
);

var_dump($updatedRestaurant);


标签: php mongodb