python使用mongodb

python使用mongodb

1.安装模块

pip3 install pymongo

2.导入使用

#1.导入模块
from pymongo import MongoClient

#2.2种方式链接数据库:用户名:密码@ip:端口号
# client=MongoClient('mongodb://root:123@localhost:27017/')
client = MongoClient('localhost', 27017)

#3.2种方式选择数据库: use 数据库
# db=client['test'] #等同于:client.db1
db = client.test #client.数据库名

#查看库下所有的集合
print(db.collection_names(include_system_collections=False))

#4、2种方式选取集合(表)
# table_user=db['user'] #等同于:db.user
table_user=db.user

#5、插入文档(数据行)
# import datetime
# user0={
# "_id":10,
# "name":"egon",
# "birth":datetime.datetime.now(),
# "age":10,
# 'hobbies':['music','read','dancing'],
# 'addr':{
# 'country':'China',
# 'city':'BJ'
# }
# }
#
# user1={
# "_id":11,
# "name":"alex",
# "birth":datetime.datetime.now(),
# "age":10,
# 'hobbies':['music','read','dancing'],
# 'addr':{
# 'country':'China',
# 'city':'weifang'
# }
# }
#
# res=table_user.insert_many([user0,user1])
# print(res)
# print(table_user.count())

#6、查找

# from pprint import pprint#格式化细
# pprint(table_user.find_one())
# for item in table_user.find():
# pprint(item)
#
# print(table_user.find_one({"_id":{"$gte":1},"name":'egon'}))

#7、更新
# table_user.update({'_id':1},{'name':'EGON'})

# 8、传入新的文档替换旧的文档(覆盖)
table_user.save(
{
"_id":3,
"name":'egon_xxx'
}
)

 

posted @ 2019-11-28 22:24  心慌得初夏  阅读(254)  评论(0编辑  收藏  举报
levels of contents