pymongo

一、安装

conda install pymongo

二、使用

1、连接

from pymongo import MongoClient

client = MongoClient(host='ip', port=27017)
# 使用方括号的方式选择数据库和集合
collection = client['db3']['stu']

2、插入数据

# 1. 插入一条数据
ret = collection.insert_one({"name": "tom", "age": 24})
# 打印_id的值
print(ret.inserted_id)
# 2. 插入多条数据 stu_lst = [{"name": "test{}".format(i), "age": 18 + i} for i in range(10)] ret = collection.insert_many(stu_lst)
# 打印所有_id的值
print(ret.inserted_ids) 注意: 在插入多条数据的情况下,使用insert_many(效率高),而不是使用insert_one
+ for循环

3、更新数据

# 1. 更新一条数据
collection.update_one({"name": "tom"}, {"$set": {"age": 100}})
# 2. 更新多条数据
ret = collection.update_many({"name": "tom"}, {"$set": {"age": 18}})
# 3. 匹配的数据条数
print(ret.matched_count)
# 4. 影响的数据条数
print(ret.modified_count)

4、查找数据

# 1. 查找一条数据
ret = collection.find_one({"name": "tom"})
print(ret)
# 2. 查找多条数据
ret = collection.find({"name": "tom"})
for i in ret:
    print(i)

注意:
查找数据和读取文件一样,游标在移动,只能遍历一次,相当于生成器
ret = collection.find() # 查找所有数据
data_list = list(ret)   # 强转,获取list
data_list的格式[{}, {}, {}, {}]

根据ObjectId查找

from bson import ObjectId
ret = collection.find_one({"_id": ObjectId("5dde12dc4141a75e1a102d80")})
print(ret)

条件

$lt     小于              {"age": {"$lt": 20}}
$gt     大于              {"age": {"$gt": 20}}
$lte    小于等于           {"age": {"$lte": 20}}
$gte    大于等于           {"age": {"$gte": 20}}
$ne     不等于             {"age": {"$ne": 20}}
$in     在范围内           {"age": {"$in": [18, 20]}}
$nin    不在范围内         {"age": {"$nin": [18, 20]}}
$regex  匹配正则表达式      {"name": {"$regex": '^M*'}}     # name以M开头  
$exists 属性是否存在        {"name": {"$exists": True}}     # name属性存在
$type   类型判断            {"age": {"$type": "int"}}       # age的类型为int
$mod    数字模操作          {"age": {"$mod": [5, 0]}}     # 年龄模5余0
$text   文本查询           {"$text": {"$search": "Mike"}}   # text类型的属性包含Mike字符串
$where  高级条件查询        {"$where": "obj.fans_count == obj.follows_count"}     # 自身粉丝数等于关注数

计算数量

collection.find().count()

排序

collection.find().sort('name', pymongo.ASCENDING)
# pymongo.ASCENDING  升序排序
# pymongo.DESCENDING 降序排序 

偏移

collection.find().sort('name', pymongo.ASCENDING).skip(2).limit(2)

5、删除数据

# 1. 删除一条数据
collection.delete_one({"name": "test1"})
# 2. 删除多条数据
ret = collection.delete_many({"name": "tom"})
# 3. 删除数据的条数
print(ret.deleted_count)
原文地址:https://www.cnblogs.com/wt7018/p/11937394.html