Python增删改查PyMongo库,以及$set 、$inc的区别实际测试

1.增删改查mongo数据库

import pymongo
# 连接
client = pymongo.MongoClient(host='localhost', port=27017)
# 指定数据库
db = client['qzc_test_btc_db']
# 指定集合名
collection = db['btc_entity_info11']

student1 = {
    'id': '20170103',
    'name': 'Kevin',
    'age': 20,
    'gender': 'male'
}
student2={
    'id': '20170202',
    'name': 'Mike',
    'age': 21,
    'gender': 'male'
}
# 插入一条数据
result1 = collection.insert_one(student1)
# 插入多条
result2 = collection.insert_many([student1, student2])


# 查询
# 插入数据后,我们可以利用find_one()或find()方法进行查询,
# 其中find_one()查询得到的是单个结果,find()则返回一个生成器对象。示例如下
result = collection.find_one({'name': 'Mike'})
# print(type(result))  # <class 'dict'>
# print(result)    # {'_id': ObjectId('5ee087371a16e25d4082d721'), 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}
# 可以发现,它多了_id属性,这就是MongoDB在插入过程中自动添加的。
count1 = collection.find().count()    #已被弃用 等价于
count2 = collection.count_documents
count = collection.find({'age': 20}).count()

# 对于数据更新,我们可以使用update()方法,指定更新的条件和更新后的数据即可
condition = {'name': 'Mike'}
student = collection.find_one(condition)
student['age'] = 25
result3 = collection.update(condition, student)


# $set操作符对数据进行更新
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student})
print(result)
print(result.matched_count, result.modified_count)
# 这里调用了update_one()方法,第二个参数不能再直接传入修改后的字典,
# 而是需要使用{'$set': student}这样的形式,其返回结果是UpdateResult类型
# 。然后分别调用matched_count和modified_count属性,可以获得匹配的数据条数和影响的数据条数。



condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)
# 这里指定查询条件为年龄大于20,然后更新条件为{'$inc': {'age': 1}},
# 也就是年龄加1,执行之后会将第一条符合条件的数据年龄加1。


# 如果调用update_many()方法,则会将所有符合条件的数据都更新,示例如下:
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition, {'$inc': {'age': 1}})
print(result)
print(result.matched_count, result.modified_count)


# 删除依然存在两个新的推荐方法——delete_one()和delete_many()。示例如下:
result = collection.delete_one({'name': 'Kevin'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)
# delete_one()即删除第一条符合条件的数据,
# delete_many()即删除所有符合条件的数据。

注意:若数据中_id重复,则报错

raise DuplicateKeyError(error.get("errmsg"), 11000, error)
pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: qzc_test_btc_db.btc_entity_info11 index: _id_ dup key: { : 100 }

2.inc 和 set 参数实例对比:
inc 只接受正数和负数的key的值,并进行增加求和(和上一次数据求和)
set 可以修改字段,没有字段则增加相应字段,

data1 = {
  "_id": 100,
  "sku": "abc123",
  "quantity": 250,
  "instock": "true",
  "reorder": "false",
  "details": { "model": "14Q2", "make": "xyz" },
  "tags": [ "apparel", "clothing" ],
  "ratings": [ { "by": "ijk", "rating": 4 } ]}

# 插入一条数据
result1 = collection.insert_one(data1)

# result = collection.update_one( { "_id": 100 },
#    { "$set":
#       {
#         "quantity": 5100,
#         "details": { "mo1del": "141Q3", "ma1ke": "x1yz" },
#         "tags": [ "coats11", "outerwe1ar", "clothi1ng" ]
#       }
#    })
#
# result = collection.update_one( { "_id": 100 },
#    { "$set":
#       {
#         "quantity": 8000} })

# result = collection.update_one( { "_id": 100 },
#    { "$inc":
#       {
#         "quantity": 5100,} })
原数据
  • 注意,若源数据库中没有数据,update_one{set} 更新无效,也不报错.
    若update_one{$inc} 去更新其他非数字字段,则报错


    set 修改

    inc 增量
inc 负数

set 设置

set可以更改字段的值为小数:


set可以更改字段的值为小数

inc 设置小数到数据库例子:



inc 修改non-numeric type字段报错:

set 可以更改原来字段的属性,这里将原来的字符串改变成了浮点数:



原数据:

set整体更改数值型:

inc整体更改数值型: _id 为 纯数字型,要报错


注意:这里不能再在要修改后的数据inc1中传入"_id",不然报错:



([UpdateOne({"_id":"a"},{"$set":{"n":"aa"}}, upsert=True),
 UpdateOne({"_id":"b"},{"$set":{"n":"b"}}, upsert=True),
UpdateOne({"_id":"c"},{"$set":{"n":"c"}}, upsert=True)]
import pymongo
# 连接
from pymongo import UpdateOne
client = pymongo.MongoClient(host='localhost', port=27017)
# 指定数据库
db = client['qzc_test_btc_db']
# 指定集合名
collection = db['btc_entity_info11']
collection.bulk_write([UpdateOne({"_id":"a"},{"$set":{"n":"aa"}}, upsert=True), UpdateOne({"_id":"b"},{"$set":{"n":"b"}}, upsert=True)])

一行bulk_write:

pymongo.MongoClient(host='localhost', port=27017)['qzc_test_btc_db']['btc_entity_info11'].bulk_write([UpdateOne({"_id":"12321a"},{"$set":{"得分n":"a12321a"}}, upsert=True), UpdateOne({"_id":"递四方速递b"},{"$set":{"n":"是的2323b"}}, upsert=True)])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值