使用pymongo對MongoDB進行的各種操作,下載相應平台的版本,解壓即可。為方便使用,將bin路徑添加到系統path環境變數里。其中mongod是伺服器,mongo是客戶shell,然後創建數據文件目錄:在c盤下創建data文件夾,裡面創建db文件夾。下面學步園小編來講解下Python怎麼調用MongoDB?Python調用MongoDB有哪些特點?
Python怎麼調用MongoDB
安裝對應語言的Driver,Python安裝pymongo
$easy_installpymongo
使用方法總結,摘自官方教程
創建連接
>>>importpymongo
>>>connection=pymongo.Connection('localhost',27017)
切換資料庫
>>>db=connection.test_database
獲取collection
>>>collection=db.test_collection
db和collection都是延時創建的,在添加Document時才真正創建
文檔添加,_id自動創建
>>>importdatetime
>>>post={"author":"Mike",
..."text":"Myfirstblogpost!",
..."tags":["mongodb","python","pymongo"],
..."date":datetime.datetime.utcnow()}
>>>posts=db.posts
>>>posts.insert(post)
ObjectId('...')
批量插入
>>>new_posts=[{"author":"Mike",
..."text":"Anotherpost!",
..."tags":["bulk","insert"],
..."date":datetime.datetime(2009,11,12,11,14)},
...{"author":"Eliot",
..."title":"MongoDBisfun",
..."text":"andprettyeasytoo!",
..."date":datetime.datetime(2009,11,10,10,45)}]
>>>posts.insert(new_posts)
[ObjectId('...'),ObjectId('...')]
獲取所有collection(相當於SQL的showtables)
>>>db.collection_names()
[u'posts',u'system.indexes']
獲取單個文檔
>>>posts.find_one()
{u'date':datetime.datetime(...),u'text':u'Myfirstblogpost!',u'_id':ObjectId('...'),u'author':u'Mike',u'tags':[u'mongodb',u'python',u'pymongo']}
查詢多個文檔
>>forpostinposts.find():
...post
...
{u'date':datetime.datetime(...),u'text':u'Myfirstblogpost!',u'_id':ObjectId('...'),u'author':u'Mike',u'tags':[u'mongodb',u'python',u'pymongo']}
{u'date':datetime.datetime(2009,11,12,11,14),u'text':u'Anotherpost!',u'_id':ObjectId('...'),u'author':u'Mike',u'tags':[u'bulk',u'insert']}
{u'date':datetime.datetime(2009,11,10,10,45),u'text':u'andprettyeasytoo!',u'_id':ObjectId('...'),u'author':u'Eliot',u'title':u'MongoDBisfun'}
加條件的查詢
>>>posts.find_one({"author":"Mike"})
高級查詢
>>>posts.find({"date":{"$lt":d}}).sort("author")
統計數量
>>>posts.count()
3
加索引
>>>frompymongoimportASCENDING,DESCENDING
>>>posts.create_index([("date",DESCENDING),("author",ASCENDING)])
u'date_-1_author_1'
查看查詢語句的性能
>>>posts.find({"date":{"$lt":d}}).sort("author").explain()["cursor"]
u'BtreeCursordate_-1_author_1'
>>>posts.find({"date":{"$lt":d}}).sort("author").explain()["nscanned"]
2
附自己總結的一點小心得,僅供參考
缺點
不是全盤取代傳統資料庫(NoSQLFan:是否能取代需要看應用場景)
不支持複雜事務(NoSQLFan:MongoDB只支持對單個文檔的原子操作)
文檔中的整個樹,不易搜索,4MB限制?(NoSQLFan:1.8版本已經修改為16M)
特點(NoSQLFan:作者在這裡列舉的很多只是一些表層的特點):
文檔型資料庫,表結構可以內嵌
沒有模式,避免空欄位開銷(SchemaFree)
分散式支持
查詢支持正則
動態擴展架構
32位的版本最多只能存儲2.5GB的數據(NoSQLFan:最大文件尺寸為2G,生產環境推薦64位)
以上就是關於「Python怎麼調用MongoDB?Python調用MongoDB有哪些特點」的內容,希望對大家有用。更多資訊請關注學步園。學步園,您學習IT技術的優質平台!