学习的测试代码:
#!/urs/bin/env python
#!-*-coding:utf-8 -*-
import pymongo
#连接数据库
def connect(db_name):
fwh_client = pymongo.MongoClient("mongodb://localhost:27017")
fwh_db = fwh_client[db_name]
return fwh_db
#插入文档
def insert_collection(db,col_name):
fwh_col = db[col_name]
#准备插入的字典
dict1={"title":"傅伟活_test05","description":"简介简介", "by":"python","url":"python.com","tags":[11,12,13,14],"likes":304}
fwh_col.insert_one(dict1)
#查找collction.fine({query},{display})
#注意,display非空,query没有为空,全查找,query的{}不可以去掉
#注意display,除了_id,可以为0,1以外,其他的都需要统一用0不显示,1显示
def fwh_viwe(db,col_name):
test_col=db[col_name]
x = test_col.find_one({"url":{"$gt":"t"}},{"_id":0,"title":1,"url":1})
for xin test_col.find({"url":{"$gt":"m"}},{"_id":0,"title":1,"url":1}):
print(x)
for xin test_col.find({},{"_id":0,"title":1,"url":1,"likes":1}):
print(x)
def fwh_change(db,col_name):
test_col = db[col_name]
test_col.update_one({"by":{"$regex":"(.+2)"}},{"$set":{"likes":"151"}})
def fwh_delect(db,col_name):
test_col = db[col_name]
test_col.delete_one({"url":"163.com"})
if __name__ =="__main__":
db_test=connect("test")#连接数据库
#insert_collection(db_test,"test2")#插入文档
fwh_viwe(db_test,"test2")#查看文档
#fwh_change(db_test,"test2")#改文档
#fwh_delect(db_test,"test2")
网友评论