MongoDB开发系列-集合更新

本文主要介绍MongoDB数据库中Update的主要操作场景,阅读本篇文章您将了解到以下内容

MongoDB中Update操作定义

MongoDB中SQl更新使用描述

MongoDB中操作符使用描述

相关代码示例

基础环境

PHP 7.2.18 

ThinkPhp5/YII2

ThinkPhp5框架Mongo驱动  "topthink/think-mongo": "^1.2",

mongodb驱动

"yiisoft/yii2-mongodb": "^2.1",

Update操作定义

相关参数如下

query: update的查询条件,类似sql update查询内where后面的。

update: update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的

upsert: 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。

multi: 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。

writeConcern:可选,抛出异常的级别。

只更新一条记录

db.col.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } );

全部更新

db.col.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true );

只添加一条记录

db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false );

全部添加进去

db.col.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true );

在MongoDb中,进行更新操作时,可以指定参数,决定当满足更新条件的记录不存在时,是否直接插入数据。

db.getCollection('status').update(

{'id':{$eq:1}},

{$set:{'lock':{'status':new NumberLong(0),'sort':new NumberLong(0)}}},

{multi:true}

)

SQL更新

ThinkPhp5+think-mongo

数据库配置如下

'type' => '\think\mongo\Connection',

    // 服务器地址

    // 服务器地址

    // 服务器地址

    'hostname'      => '',

    // 数据库名

    'database'      => 'dbname',

    // 用户名

    'username'      => 'usesname',

    // 密码

    'password'      => 'pwd',       

    // 端口

    'hostport'      => '10000', //可修改


引用包

use think\Db;

常规数据更新场景,查询是否存在并插入

数据模型类EpayMonitorReportModel

$report= newEpayMonitorReportModel();

$where= array("datepark"=>$data["datepark"]);

$success=0;

//检测是否存在

$result=Db::name($this->collection_name)->where($where)->select();

Log::write(Db::getLastSql(),'sql');

if(is_array($result)&&sizeof($result)==1) {

Log::write("已经创建统计过当天记录","info");

}else{

    $success=Db::name($this->collection_name)->insert($data,true);

}

return succes



YII2+yiisoft/yii2-mongodb

数据库配置

主要配置包括class和dsn属性,多个复制集合实例在dsn中配置

'class' => '\yii\mongodb\Connection',

'dsn' => 'mongodb://user:pqssword@s1._test.mongodb.domain.cn:30000,s2.mongodb.domain.cn:30000,s3._test.mongodb.domain.cn:30000/databasename',

引用包

use yii\mongodb\ActiveRecord;

use yii\mongodb\Query;

更新操作主要使用 self::updateAll接口

   /**

    *  CollectionName

    *

    * @return mixed

    */

    public static function collectionName()

    {

        return 'epay_monitor_report';

    }

更新

$result = $query->select(['id'])

            ->from(self::collectionName())

            ->where($where)->one();

        if (is_array($result)) {

            if (!is_array($result['oper'])) {

                $result['oper'] = [];

            }

           $success = self::updateAll($businessProfile, $where);

        }

        return $success == 1;

操作符更新

$push操作

ThinkPhp5框架,Mongo驱动  "topthink/think-mongo": "^1.2",

数据集模式

用户角色user_roles关联关系集合1:N

{

    "_id" : ObjectId("590894e673547cfecdbf1147"),

    "userid" : 2425,

    "state" : 0,

    "create_time" : ISODate("2018-05-11T07:31:44.000Z"),

    "update_time" : ISODate("2018-07-12T17:00:01.000Z"),

    "enable_alarm" : 0,

    "rid" : [

        865,

        864,

        856,

        235

    ],

}

需求

如何实现rid节点中增加元素?

实现

public function addRoleId($userId,$rid)

{

$where = ['userid' => $userId];

$data = [

'parkid' =>

            [

                '$push',

                $rId

            ],

'update_time' => TimeUtility::getCurrentUtcTime(),

];

Db::name('user_roles')->where($where)->update($data);

}

Python

以下代码是通过$push操作符,按照时间顺序(chronological order)把数组追加到集合的comments节点下。

数据集模式

{

    _id: ObjectId(...),

    ... lots of topic data ...

    comments: [

        { posted: ISODateTime(...),

          author: { id: ObjectId(...), name: 'Rick' },

          text: 'This is so bogus ... ' },

      ... ]

}

db.discussion.update(

    { 'discussion_id': discussion_id },

    { '$push': { 'comments': {

        'posted': datetime.utcnow(),

        'author': author_info,

        'text': comment_text } } } )


$inc操作

数据集模式

{

  _id: 1,

  sku: "abc123",

  quantity: 10,

  metrics: {

    orders: 2,

    ratings: 3.5

  }

}

db.products.update(

  { sku: "abc123" },

  { $inc: { quantity: -2, "metrics.orders": 1 } }

)

结果

{

  "_id" : 1,

  "sku" : "abc123",

  "quantity" : 8,

  "metrics" : {

      "orders" : 3,

      "ratings" : 3.5

  }

}

以上内容简单介绍了Update操作中,$push和$inc的操作符的使用,MonngoDb本身提供了众多操作符,用于简化操作。我们在开发过程中,可以通过具体的场景选择合适的操作符。

具体含义和用法参考官方文档 https://docs.mongodb.com/manual/reference/operator/update-field/

-----------------------------------------------------------------

文章已同步到公众号《图南科技》欢迎关注

![MongoDB最佳实践-图南科技](https://upload-images.jianshu.io/upload_images/5651-7678fc0994abb2fd.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/258/format/webp)

你可能感兴趣的:(MongoDB开发系列-集合更新)