本文实例讲述了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()
</li>
</ul>
</li>
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()
<!--EndFragment--></li>
</ul>
</li>
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()
</li>
</ul>
</li>
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()
</li>
</ul>
</li>
想了解更多,可以参考pymongo官方文档:http://api.mongodb.com/python/current/api/pymongo/
希望本文所述对大家Python程序设计有所帮助。
Powered By python教程网 鲁ICP备18013710号
python博客 - 小白学python最友好的网站!