- 論壇徽章:
- 0
|
Python調用MongoDB使用心得
本文是一個Python 使用MongoDB的簡單教程,將使用pymongo對MongoDB進行的各種操作進行了簡單的匯總,NoSQLFan進行了簡單整理,使用Python的同學可以看一看。
下載相應平臺的版本,解壓即可。為方便使用,將bin路徑添加到系統(tǒng)path環(huán)境變量里。其中mongod是服務器,mongo是客戶shell,然后創(chuàng)建數(shù)據(jù)文件目錄:在c盤下創(chuàng)建data文件夾,里面創(chuàng)建db文件夾。
基本使用:
安裝對應語言的Driver,Python 安裝 pymongo
$ easy_install pymongo使用方法總結,摘自官方教程
創(chuàng)建連接
>>> import pymongo
>>> connection=pymongo.Connection('localhost',27017)切換數(shù)據(jù)庫
>>> db = connection.test_database獲取collection
>>> collection = db.test_collectiondb和collection都是延時創(chuàng)建的,在添加Document時才真正創(chuàng)建
文檔添加,_id自動創(chuàng)建
>>> import datetime
>>> post = {"author": "Mike",
... "text": "My first blog post!",
... "tags": ["mongodb", "python", "pymongo"],
... "date": datetime.datetime.utcnow()}
>>> posts = db.posts
>>> posts.insert(post)
ObjectId('...')批量插入
>>> new_posts = [{"author": "Mike",
... "text": "Another post!",
... "tags": ["bulk", "insert"],
... "date": datetime.datetime(2009, 11, 12, 11, 14)},
... {"author": "Eliot",
... "title": "MongoDB is fun",
... "text": "and pretty easy too!",
... "date": datetime.datetime(2009, 11, 10, 10, 45)}]
>>> posts.insert(new_posts)
[ObjectId('...'), ObjectId('...')]獲取所有collection(相當于SQL的show tables)
>>> db.collection_names()
[u'posts', u'system.indexes']獲取單個文檔
>>> posts.find_one()
{u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}查詢多個文檔
>> for post in posts.find():
... post
...
{u'date': datetime.datetime(...), u'text': u'My first blog post!', 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'Another post!', 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'and pretty easy too!', u'_id': ObjectId('...'), u'author': u'Eliot', u'title': u'MongoDB is fun'}加條件的查詢
>>> posts.find_one({"author": "Mike"})高級查詢
>>> posts.find({"date": {"$lt": d}}).sort("author")統(tǒng)計數(shù)量
>>> posts.count()
3加索引
>>> from pymongo import ASCENDING, DESCENDING
>>> posts.create_index([("date", DESCENDING), ("author", ASCENDING)])
u'date_-1_author_1'查看查詢語句的性能
>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]
u'BtreeCursor date_-1_author_1'
>>> posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]
2附自己總結的一點小心得,僅供參考
缺點
不是全盤取代傳統(tǒng)數(shù)據(jù)庫(NoSQLFan:是否能取代需要看應用場景)
不支持復雜事務(NoSQLFan:MongoDB只支持對單個文檔的原子操作)
文檔中的整個樹,不易搜索,4MB限制?(NoSQLFan:1.8版本已經(jīng)修改為16M)
特點(NoSQLFan:作者在這里列舉的很多只是一些表層的特點):
文檔型數(shù)據(jù)庫,表結構可以內嵌
沒有模式,避免空字段開銷(Schema Free)
分布式支持
查詢支持正則
動態(tài)擴展架構
32位的版本最多只能存儲2.5GB的數(shù)據(jù)(NoSQLFan:最大文件尺寸為2G,生產環(huán)境推薦64位)
名詞對應
一個數(shù)據(jù)項叫做 Document(NoSQLFan:對應MySQL中的單條記錄)
一個文檔嵌入另一個文檔(comment 嵌入 post)叫做 Embed
儲存一系列文檔的地方叫做 Collections(NoSQLFan:對應MySQL中的表)
表間關聯(lián),叫做 Reference |
|