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