python 操作mongodb

來源:互聯網
上載者:User
import pymongo,sys
from pymongo import MongoClient
client = MongoClient(host="localhost:27017",read_preference=pymongo.read_preferences.ReadPreference.PRIMARY_PREFERRED)
db = client.database
db.authenticate("database","passwd")

1.search
pi = db.locinfo.find({"con":p}) #search
pi = db.locinfo.find_one({"con":p})
print pi
{u'city': u'\u56fe\u6728\u8212\u514b\u5e02', u'wid': u'101130908', u'zip': u'843900', u'pro': u'\u65b0\u7586\u7ef4\u543e\u5c14\u81ea\u6cbb\u533a', u'wkey': u'\u56fe\u6728\u8212\u514b\u5e02', u'acode': u'0998', u'_id': u'txpcx5', u'fix': True, u'con': u'\u56fe\u6728\u8212\u514b\u5e02'}


2.update
db.locinfo.update({"con":p},{'$set':{"con":zc}}) # update one item
×××××××××××××××批量update ××× multi=True ××××××××××××××××××××××××××××××××
db.locinfo.update({"con":lon},{'$set':{"wkey": sht }},multi=True) #ok,# update multiple items
××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

3。insert # 插入數組,及一般字元竄
db.wbinfo.insert({"city":cityname,"jiaojing":[jiaojing],"lukuang":"lukuang,"})

4。push 、 pop 插入數組,刪除數組元素
db.wbinfo.update({"city":"六安市"},{'$push':{"jiaojing":"two","lukuang":"lk"}})
db.wbinfo.update({"city":"六安市"},{'$pop':{"jiaojing":"two","lukuang":"lk"}})

5. 正則查詢
res = db.devices.find({'$and':[{'stats.devcaps':{'$exists':True}},{'stats.fwver':{'$regex':'.*N91|N92.*'}}]}) # stats.fwver 欄位包含字元 'N91' 或者 'N92'

6.字典
if devcap.has_key('dev') and devcap.has_key('cap'):

7.
python操作mongodb根據_id查詢資料的代碼
ObjectId pymongo python
如果pymongo的版本號碼小於2.2,使用下面的語句匯入ObjectId
from pymongo.objectid import ObjectId

如果pymongo的版本號碼大於2.2,則使用下面的語句
from bson.objectid import ObjectId
查詢代碼如下:
collection.find_one({'_id':ObjectId('50f0d76347f4ec148890ef1e')})
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.