MongoDB的Python接口 PyMongo
fmms 13年前
<div id="p_fullcontent" class="detail"> <p>PyMongo 是 MongoDB 的 Python 接口开发包。</p> <p>示例代码:</p> <p>创建Connection时,指定host及port参数<br /> >>> import pymongo<br /> >>> conn = pymongo.Connection(host='127.0.0.1',port=27017)<br /> <br /> 连接数据库<br /> >>> db = conn.ChatRoom<br /> 或<br /> >>> db = conn['ChatRoom']<br /> <br /> 连接聚集<br /> >>> account = db.Account<br /> 或<br /> >>> account = db["Account"]<br /> <br /> 查看全部聚集名称<br /> >>> db.collection_names()<br /> <br /> 查看聚集的一条记录<br /> >>> db.Account.find_one()<br /> >>> db.Account.find_one({"UserName":"keyword"})<br /> <br /> 查看聚集的字段<br /> >>> db.Account.find_one({},{"UserName":1,"Email":1})<br /> {u'UserName': u'libing', u'_id': ObjectId('4ded95c3b7780a774a099b7c'), u'Email': u'libing@35.cn'}<br /> >>> db.Account.find_one({},{"UserName":1,"Email":1,"_id":0})<br /> {u'UserName': u'libing', u'Email': u'libing@35.cn'}<br /> <br /> 查看聚集的多条记录<br /> >>> for item in db.Account.find():<br /> item<br /> >>> for item in db.Account.find({"UserName":"libing"}):<br /> item["UserName"]<br /> <br /> 查看聚集的记录统计<br /> >>> db.Account.find().count()<br /> >>> db.Account.find({"UserName":"keyword"}).count()<br /> <br /> 聚集查询结果排序<br /> >>> db.Account.find().sort("UserName") --默认为升序<br /> >>> db.Account.find().sort("UserName",pymongo.ASCENDING) --升序<br /> >>> db.Account.find().sort("UserName",pymongo.DESCENDING) --降序<br /> <br /> 聚集查询结果多列排序<br /> >>> db.Account.find().sort([("UserName",pymongo.ASCENDING),("Email",pymongo.DESCENDING)])</p> <p><br /> 添加记录<br /> >>> db.Account.insert({"AccountID":21,"UserName":"libing"})<br /> <br /> 修改记录<br /> >>> db.Account.update({"UserName":"libing"},{"$set":{"Email":"libing@126.com","Password":"123"}})<br /> <br /> 删除记录<br /> >>> db.Account.remove() -- 全部删除<br /> >>> db.Test.remove({"UserName":"keyword"})<br /> <br /> <span style="font-weight:bold;">项目地址:</span><a style="font-weight:bold;" href="/misc/goto?guid=4958189197891343922" target="_blank">http://pypi.python.org/pypi/pymongo/</a></p> </div>