需求场景:

`test` 表中的 `id` = 1 数据 `num` 字段 自增+1或者-1

MySQL下:

UPDATE `test`  SET `num` = `num` + 1  WHERE  `id` = 1
UPDATE `test`  SET `num` = `num` - 1  WHERE  `id` = 1

MongoDB下:

 // 增
 db.test.findAndModify(
      {
         query:{ "id" : 1 },
         update: { $inc:{ "num":1 } },
         "new":true
      });
      
 // 减
  db.test.findAndModify(
      {
         query:{ "id" : 1 },
         update: { $inc:{ "num": -1 } },
         "new":true
      });

这里介绍下MongoDB的findAndModify方法

findAndModify属于原子操作模型数据

所谓原子操作就是要么这个文档保存到Mongodb,要么没有保存到Mongodb,不会出现查询到的文档没有保存完整的情况。

MongoDB findAndModify方法的语法如下。

db.collection.findAndModify({

    query: <document>,

    sort: <document>,

    new: <boolean>,

    fields: <document>,

    upsert: <boolean>

})

参数说明如下:

query: Defines the selection criteria as to which record needs modification.

query :定义关于哪些记录需要修改的选择标准。

sort: Determines which document should be modified when the selection criteria retrieves multiple documents.

sort :确定选择标准检索多个文档时应修改的文档。

new: indicates that the modified document will be displayed.

new :表示将显示修改后的文档。

fields: specifies the set of fields to be returned.

fields :指定要返回的字段集。

upsert: creates a new document if the selection criteria fails to retrieve a document.

upsert :如果选择标准无法检索文档,则创建一个新文档。

PHP7语法如下:

$param   = [
    'findAndModify' => "test",
    'query'         => ["id" => 1],
    'update'        => ['$inc' => ["num" => 1]],
    'new'           => true,
];
$command = new \MongoDB\Driver\Command($param);
$result  = (new \MongoDB\Driver\Manager("mongodb://localhost:27017", []))->executeCommand("test", $command);
$res     = $result->toArray();
$value   = (array)$res[0];
var_dump($value['value'] ?? NULL);


打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开微信扫一扫,即可进行扫码打赏哦

分享到
  • QQ好友
  • 微信好友
  • 新浪微博