Python调用MongoDB使用心得
生活随笔
收集整理的這篇文章主要介紹了
Python调用MongoDB使用心得
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文是一個Python?使用MongoDB的簡單教程,將使用pymongo對MongoDB進行的各種操作進行了簡單的匯總,NoSQLFan進行了簡單整理,使用Python的同學可以看一看。
下載相應平臺的版本,解壓即可。為方便使用,將bin路徑添加到系統path環境變量里。其中mongod是服務器,mongo是客戶shell,然后創建數據文件目錄:在c盤下創建data文件夾,里面創建db文件夾。
基本使用:
安裝對應語言的Driver,Python 安裝 pymongo
$ easy_install pymongo使用方法總結,摘自官方教程
創建連接
>>> import pymongo >>> connection=pymongo.Connection('localhost',27017)切換數據庫
>>> db = connection.test_database獲取collection
>>> collection = db.test_collectiondb和collection都是延時創建的,在添加Document時才真正創建
文檔添加,_id自動創建
>>> 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")統計數量
>>> 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附自己總結的一點小心得,僅供參考
缺點
- 不是全盤取代傳統數據庫(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
總結
以上是生活随笔為你收集整理的Python调用MongoDB使用心得的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mongoDB简明教程-python
- 下一篇: Spark - 大数据Big Data处