(编辑:jimmy 日期: 2024/11/12 浏览:2)
本文实例讲述了python使用pymongo与MongoDB基本交互操作。分享给大家供大家参考,具体如下:
首发时间:2018-03-18 20:11
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相关内容感兴趣的读者可查看本站专题:《Python常见数据库操作技巧汇总》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。