python操作mongodb数据库

1、连接数据库,在数据库里面创建一个类,删除一个类

导入pymongo库,用MongoClient连接,看看有各个数据库名字

from pymongo import *

client = MongoClient('mongodb://kb314:[email protected]:30011') # 创建连接
print(client.database_names()) # 看看这个客户端里面有多少个数据库,打印数据库名字

选择一个数据库,看看里面有多少集合

db = client['tweet_stream']  # 选择一个数据库
print(db.collection_names()) # 看看这个数据库里面有哪些集合

新建一个集合

#新建一个集合
db.create_collection('test')
print(db.collection_names())

在这里插入图片描述
可以看出,我们在数据库’tweet_stream’下创建了一个集合:test

我们可以用db[‘test’].drop()删除这个集合

2、向集合中插入数据和删除数据

#向集合中插入一个数据
collection = db['test']
data = {'name': 'cindy', 'age':21, 'school': 'uestc'}
collection.insert_one(data) # 插入一个
manyData = [{'name': 'hong', 'age': '22'}, {'name': 'cindy', 'age': 21}]
collection.insert_many(manyData) # 插入多个数据
collection.delete_one({'name': 'cindy', 'age':21, 'school': 'uestc'}) # 删除符合该条件的一个数据
collection.delete_many({'name': 'cindy'}) # 删除符合该条件的多个数据
collection.delete_many(}) # 删除所有数据

3、使用PyMongo查询数据

无条件的查找

# 查找一个数据
item = collection.find_one()
print(item)
# 查找所有数据
cursor = collection.find()
for term in cursor:
    print(term)

有条件查找

data = [
    {'name': 'hong', 'age': 22},
    {'name': 'cindy', 'age': 21},
    {'name': 'cindy', 'age': 22}
]

cursor = collection.find({'name': 'cindy'}) #则cursor里面包含后两条信息
#多个查找条件用花括号括起来
cursor = collection.find({'name': 'cindy', 'age': 22}) #则cursor里面包含最后一条信息
#多个查找条件是或的逻辑
cursor = collection.find({"$or":[{'name': 'cindy'}, {'age': 22}]}) #则cursor里面包含所有信息
# 使用大于操作符
cursor = collection.find({'age': {'$gt':21}}) # cursor里面包含age大于21岁的所有数据
# 使用小于操作符
cursor = collection.find({'age': {'$lt':22}}) # cursor里面包含age小于22岁的所有数据
# 将结果进行排序,ASCENDING表示升序,DESCENDING表示降序
cursor = cursor = collection.find().sort([('age', ASCENDING), ('name', DESCENDING)]) # 所有数据按照age升序,名字降序
for item in cursor: # 打印结果
    print(item)

4、更新和替换文档

更新文档

result1 = collection.update_one({'name': 'hong'}, {"$set": {'age': 99}}) # 将name为hong的一条数据里面的age改为99
print(result1.matched_count) # 查看修改了多少条信息
for item in collection.find():
    print(item)
result2 = collection.update_many({'name': 'cindy'}, {"$set": {'age': 99}}) # 将name为cindy的所有数据里面的age改为99
print(result2.matched_count) # 查看修改了多少条信息
for item in collection.find():
    print(item)

替换操作

# 将所有name为hong的文档都替换成新的数据{'name': 'cindy','age': 21}
result = collection.replace_one(
    {'name': 'hong'},
    {
        'name': 'cindy',
        'age': 21
    }
)
print(result.matched_count) # 打印符合筛选器条件的文档数目
print(result.modified_count) # 打印更新操作中被修改的文档数目

你可能感兴趣的:(数据库)