python 更新 MongoDB

3.python更新MongoDB

参考:
1 python 写入 MongoDB

2 python 读取 MongoDB

4 python删除MongoDB

实例:

from pymongo import MongoClient
#连接mongodb
connect = MongoClient('localhost')
#连接库
db = connect.demo
#连接集合
emp = db.employees
#1.更新一条数据
emp.update_one(
    {'name':'王五'},
    {'$set':{
        'name':'王舞',
        'sex':'女汉子'
        }
    }
)
# #2.更新多条数据
# #2.1更新所有,无条件
emp.update_many(
    {},
    {'$inc':{'age':1}}  #年龄增加1
)
#2.2有条件的更新
emp.update_many(
    {'name':{"$in":['张三','李四']}},
    {'$set':{'age':25}},  #没有字段也自动添加
    upsert=True
)
#生成时间
emp.update_many(
    {'name':{'$in':['张三','李四']}},
    {'$currentDate':{
        'create_time':True,   #相当于{'$type':'Date'}
        'mod_time':{'$type':'timestamp'}  #时间戳
    }}
)
#
emp.update_many(
    {'name':'赵六'},
    {'$currentDate':{
        'create_time':True,   #相当于{'$type':'Date'}
        'mod_time':{'$type':'timestamp'}  #时间戳
    }},
     upsert = True    #赵六不存在,则新建一个
)
#更新子字段
emp.update_one(
    {'name':'李四'},
    {'$set':{
        'habit':{
        'habit1':'学习',
        'habit2':'运动'
        }}
    }
)

你可能感兴趣的:(python,MongoDB,更新)