前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MongoDB之Update

MongoDB之Update

作者头像
needrunning
发布2019-07-04 10:55:19
1.5K0
发布2019-07-04 10:55:19
举报
文章被收录于专栏:图南科技图南科技

本文主要介绍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


插图取自官网 https://www.mongodb.com/new

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-07-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 图南科技 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Update操作定义
  • SQL更新
  • 操作符更新
    • $push操作
      • db.discussion.update(
        • $inc操作
          • db.products.update(
          相关产品与服务
          云数据库 MongoDB
          腾讯云数据库 MongoDB(TencentDB for MongoDB)是腾讯云基于全球广受欢迎的 MongoDB 打造的高性能 NoSQL 数据库,100%完全兼容 MongoDB 协议,支持跨文档事务,提供稳定丰富的监控管理,弹性可扩展、自动容灾,适用于文档型数据库场景,您无需自建灾备体系及控制管理系统。
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档