MongoDb 的Python支援

來源:互聯網
上載者:User

本文是一個Python 使用MongoDB的簡單教程,將使用pymongo對MongoDB進行的各種操作進行了簡單的匯總,我們進行了簡單整理,使用Python的同學可以看一看。

下載相應平台的版本,解壓即可。為方便使用,將bin路徑添加到系統path環境變數裡。其中mongod是伺服器,mongo是客戶shell,然後建立資料檔案目錄:在c盤下建立data檔案夾,裡面建立db檔案夾。

基本使用:

安裝對應語言的Driver,Python 安裝 pymongo

1 $ easy_install pymongo

使用方法總結,摘自官方教程

建立串連

1 >>> import pymongo
2 >>> connection=pymongo.Connection('localhost',27017)

切換資料庫

1 >>> db = connection.test_database

擷取collection

1 >>> collection = db.test_collection

db和collection都是延時建立的,在添加Document時才真正建立

文檔添加,_id自動建立

1 >>> import datetime
2 >>> post = {"author": "Mike",
3 ...         "text": "My first blog post!",
4 ...         "tags": ["mongodb", "python", "pymongo"],
5 ...         "date": datetime.datetime.utcnow()}
6 >>> posts = db.posts
7 >>> posts.insert(post)
8 ObjectId('...')

批量插入

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']

擷取單個文檔

1 >>> posts.find_one()
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():
2 ...   post
3 ...
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 >>> posts.count()
2 3

加索引

1 >>> from pymongo import ASCENDING, DESCENDING
2 >>> posts.create_index([("date", DESCENDING), ("author", ASCENDING)])
3 u'date_-1_author_1'

查看查詢語句的效能

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"]
4 2

附自己總結的一點小心得,僅供參考

缺點

  • 不是全盤取代傳統資料庫(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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.