1、 连接 MongoDB
myClient = MongoClient("mongodb://localhost:27017/")
# myClient = MongoClient(host='localhost', port=27017)
2、指定数据库 没有则创建
myDB = myClient["mydb"]
# myDB = myClient.mydb
3、指定集合 没有则创建
myCol = myDB['mycol']
# myCol = myDB.mycol
4、插入文档
# 单条插入文档
doc = {
'name': "张三",
'age': 20,
'gender': 'male',
'score': 97
}
# insert() 执行后返回_id的值
rs = myCol.insert(doc)
# rs = myCol.insert_one(doc)
print(rs)
# 多条插入
student1 = {
'id': '2022012101',
'name': '小明',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '2022012102',
'name': '小红',
'age': 21,
'gender': 'female'
}
result = myCol.insert([student1, student2])
# result = myCol.insert_many([student1, student2])
print(result)
5、查询数据和更新
# 查询数据(没有返回None)
# 查询全部
for i in mycol.find():
print(i)
# 查询name = zhangsan
for i in mycol.find({"name": "zhangsan"}):
print(i)
print(mycol.find_one({"name": "zhangsan"}))
# 更新数据
myQuery = {'name':'zhangsan'}
newValues = {'$set': {'name': 'xiaoming'}
mycol.update_one(myQuery, newValues)
6、删除
# 删除
# 删除name=zhangsan的全部记录
mycol.remove({'name': 'zhangsan'})
for i in mycol.find():
print(i)
# 删除name=lisi2
id = mycol.find_one({"name": "lisi2"})["_id"]
mycol.remove(id)
for i in mycol.find():
print(i)
# 删除集合里的所有记录
mydb.users.remove()
7、其他操作
# mongodb 的条件操作符
# (>) 大于 - $gt
# (<) 小于 - $lt
# (>=) 大于等于 - $gte
# (<= ) 小于等于 - $lte
# (==) 等于 $eq
# (!=) 不等于 $ne
# 查询集合中age大于20的所有记录
for i in mycol.find({"age": {"$gt": 20}}):
print(i)
# 排序 1升序,-1降序
for i in mycol.find().sort([("age", 1)]):
print(i)
pass
# limit()方法用来读取指定数量的数据
# skip()方法用来跳过指定数量的数据
# 下面表示跳过两条数据后读取6条
for i in mycol.find().skip(2).limit(3):
print(i)
pass
# in on all
# 找出age是19、20、21的数据
for i in mycol.find({"age": {"$in": (19, 20, 21)}}):
print(i)
# 找出age是20或21的记录
for i in mycol.find({"$or": [{"age": 20},
{"age": 21}]}):
print(i)
8、在已存在的mongodb集合中添加字段删除字段
CONGIF_MONGODB_DB = pymongo.MongoClient("mongodb://localhost:27017/")
CONGIF_MONGODB_DB.log.odd_break_rule.update({}, {'$set': {'out_trade_no': 0}})
CONGIF_MONGODB_DB.log.odd_break_rule.update({}, {'$unset': {'out_trade_no': ''}})
9、多级目录的增删改查

# 多级目录的增删改查
dic = {"name": "zhangsan",
"age": 18,
"contact": {
"email": "1234567@qq.com",
"iphone": "11223344"}
}
mycol.insert_one(dic)
# 多级目录用. 连接
result = mycol.find_one({"contact.iphone": "11223344"})
print(result["contact"]["email"])
# 多级路径下修改操作
result = mycol.update({"contact.iphone": "11223344"}, {"$set": {"contact.email": "9999999@qq.com"}})
print(result["contact"]["iphone"])
dic = {"name": "lisi",
"age": 18,
"contact": [
{"email": "111111@qq.com",
"iphone": "111"},
{"email": "222222@qq.com",
"iphone": "222"}
]}
mycol.insert(dic)
result2 = mycol.update({"contact.1.iphone": "222"}, {"$set": {"contact.1.email": "222222@qq.com"}})
print(result2["contact"][1]["email"])
View Code