这篇文章主要讲解了python使用pymongo与MongoDB基本交互的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
pymongo的使用:
pip3 pymongo
import pymongo
conn=pymongo.MongoClient(host="localhost",port=27017)
# db=conn.School #获取School数据库 db=conn['School'] #获取School数据库
# collection=db.teacher#选择teacher集合 collection=db['teacher']#选择teacher集合
import pymongo conn=pymongo.MongoClient(host="localhost",port=27017) db=conn['School'] collection=db['teacher'] rel=collection.find() print([r for r in rel]) rel=collection.find({"name":"Alex"}) print([r for r in rel]) # rel=collection.find({"age":{"$gt":20}}) rel=collection.find({"$or":[{"name":"Amy"},{"name":"Alex"}]}) print([r for r in rel]) rel=collection.find_one({"name":"jack"}) print(rel) print(rel['name'])#单个文档情况下可用来取出指定值 conn.close()
import pymongo conn=pymongo.MongoClient(host="localhost",port=27017) db=conn['School'] collection=db['teacher'] collection.insert({"name":"Job","course":"career"}) # col.insert(document)#**DEPRECATED** - Use :meth:`insert_one` or :meth:`insert_many` instead. # insert是不推荐用了,建议使用insert_one,insert_many collection.insert_one({"name":"Job1","course":"career1"}) t1={"name":"Job2","course":"career2"} t2={"name":"Job3","course":"career3" } collection.insert_many([t1,t2]) conn.close()
import pymongo conn=pymongo.MongoClient(host="localhost",port=27017) db=conn['School'] collection=db['teacher'] # rel=collection.update({"name":"Job1"},{ "$set":{"name":"Bob"}})#不推荐使用 # collection.update_one({"name":"Job"},{ "$set":{"name":"Bob"}}) collection.update_many({"name":"Job1"},{ "$set":{"name":"Bob" }}) conn.close()
import pymongo conn=pymongo.MongoClient(host="localhost",port=27017) db=conn['School'] collection=db['teacher'] # collection.remove({"name":"Bob"}) # collection.delete_one({"name":"Bob2"}) collection.delete_many({"name":"Job3" }) conn.close()
想了解更多,可以参考pymongo官方文档:http://api.mongodb.com/python/current/api/pymongo/
看完上述内容,是不是对python使用pymongo与MongoDB基本交互的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。