MongoDB与python 交互
一、安装pymongo
注意 :当同时安装了python2和python3,为区分两者的pip,分别取名为pip2和pip3。
推荐:https://www.cnblogs.com/thunderLL/p/6643022.html
二、MongoDB与python 交互
2.1、打开黑屏终端,启动mongodb服务,运行mongo
# encoding=utf8 from pymongo import MongoClient from bson.objectid import ObjectId import pymongo # 连接服务器 conn = MongoClient("localhost", 27017) # 连接数据库 db = conn.text # 获得集合 collection = db.sub # 添加数据 collection.insert( {'name': 'dd', 'gender': 1, 'math': 30, 'chinese': 50} ) # 查询文档 # res = collection.find() # 查询部分文档 ''' res = collection.find({"math": {"$gt": 60}}) for row in res: print(row) print(type(row)) ''' # 统计查询 ''' res = collection.find({"math": {"$gt": 60}}).count() print(res) ''' # 根据id 查询 ''' res = collection.find({"_id":ObjectId('5b927e096e92f1c1d53e548f')}) print(res[0]) ''' # 排序 ''' res = collection.find().sort("math") # 升序 res = collection.find().sort("math", pymongo.DESCENDING) for row in res: print(row) ''' # 分页查询 ''' res = collection.find().skip(3).limit(4) for row in res: print(row) ''' # 更新文档 ''' collection.update({"name": "bbb"}, {"$set": {"math": 100}}) ''' #删除 ''' collection.remove({"name": "dd"}) ''' # 断开 conn.close()
三、MongoEngine
PyMongo是将MongoDB API包装到Python中并提供传入和传出JSON的低级驱动程序。
MongoEngine或其他类似MongoKit的层将您基于MongoDB的数据映射到类似于本机Python数据库驱动程序+ SQLAlchemy作为ORM的对象。
https://stackoverflow.com/questions/5712857/pymongo-vs-mongoengine-for-django