Pymongo
#https://api.mongodb.com/python/current/tutorial.html
from pymongo import MongoClient
#1、链接
client=MongoClient('mongodb://root:123@localhost:27017/')
# client = MongoClient('localhost', 27017)
#2、use 数据库
db=client['db2'] #等同于:client.db1
#3、查看库下所有的集合
print(db.collection_names(include_system_collections=False))
#4、创建集合
table_user=db['userinfo'] #等同于:db.user
#5、插入文档
import datetime
user0={
"_id":1,
"name":"egon",
"birth":datetime.datetime.now(),
"age":10,
'hobbies':['music','read','dancing'],
'addr':{
'country':'China',
'city':'BJ'
}
}
user1={
"_id":2,
"name":"alex",
"birth":datetime.datetime.now(),
"age":10,
'hobbies':['music','read','dancing'],
'addr':{
'country':'China',
'city':'weifang'
}
}
# res=table_user.insert_many([user0,user1]).inserted_ids
# 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":2,
"name":'egon_xxx'
}
)
# pip3 install pymong
from pymongo import MongoClient
from pymongo.collection import Collection
#MongoClient('mongodb://root:123@localhost:27017/')
conn=MongoClient(host="10.0.0.5",port=27017)
# use lqz
# 你用过python中的魔法方法(init,new,str) __add__
# with __enter__ __exit__
lqz=conn.lqz # 重写了__getattr__
# lqz=conn["lqz"] # 重写了__getitem__
#lqz.users 获取表
users=lqz.users # type:Collection
# users.find({'name':"li"})
# users.insert_many()
# users.insert_one()
# update被弃用了
# users.update()
#
# users.aggregate({},{},{})
# users.delete_many()
# users.delete_one()
# print(users.find())
# for i in users.find({'name':"li"}):
# print(type(i))
#集成到django框架和flask框架