MongoDB與pymongo

首先,必須確認如下環境已經安裝:python

1. Pythonweb

2. MongoDBmongodb

3. pymongo數據庫

 

導入模塊

import pymongo

 

使用MongoClient鏈接MongoDB

from pymongo import MongoClient
client = MongoClient(host, port)

引用MongoClient來建立數據庫鏈接實例。在MongoDB中,默認的host和port以下:post

client = MongoClient('localhost', 27017)

或者使用MongoDB的URL來引用:spa

client = MongoClient('mongodb://localhost:27017/')

 

鏈接MongoDB的一個數據庫

任何一個鏈接實例均可以鏈接一個或者多個獨立的數據庫。這裏默認已有一個名爲test_db的數據庫,下面是鏈接方法:code

database = client.test_database

或者當你的數據庫名稱不符合Python標準的時候,能夠用:orm

database = client['test-database']

 

讀取一個Collection

Collection在這裏的意思是一個存儲在MongoDB中的文件集合,至關於關係型數據庫中的table。具體方法和database同樣:blog

collection = db.test_collection

或者:排序

collection = db['test-collection']

 

數據格式

數據在MongoDB中是以JSON的方式儲存的。在pymongo中使用字典的形式來保存數據。事例以下:

>>> import datetime
>>> post = {"author": "Mike",
...         "text": "My first blog post!",
...         "tags": ["mongodb", "python", "pymongo"],
...         "date": datetime.datetime.utcnow()}

 

插入一條數據

咱們使用insert_one()方法來插入一條數據

>>> posts = db.posts >>> post_id = posts.insert_one(post).inserted_id >>> post_id ObjectId('...')

若是數據不含有「_ID」,那麼當它被插入到數據庫中的時候,數據庫就會自動賦予它一個「_ID」。在整個MongoDB中,這個_ID都是惟一的。

當post這個數據被插入的時候,它也就在MongoDB中同時被建立了一個Collection。咱們能夠用以下的方法來驗證這些Collection:

>>> db.collection_names(include_system_collections=False)
[u'posts']

 

查詢一條數據

在MongoDB中最爲基礎的查詢語言就是find_one()。這種方法只能返回一條查詢結果,當有多個查詢結果符合查詢條件的時候,數據庫會返回第一條。

>>> import pprint
>>> pprint.pprint(posts.find_one())
{u'_id': ObjectId('...'),
 u'author': u'Mike',
 u'date': datetime.datetime(...),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}

返回的結果也是以字典的方式呈現的。

一樣地,這個方法也支撐具體的條件查詢,例如,咱們想要得到做者爲Mike的數據:

>>> pprint.pprint(posts.find_one({"author": "Mike"}))
{u'_id': ObjectId('...'),
 u'author': u'Mike',
 u'date': datetime.datetime(...),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}

若是咱們試着查詢另外一個不存在的做者,例如Eliot,返回的結果就是空:

>>> posts.find_one({"author": "Eliot"})
>>>

 

經過_ID查詢

因爲_ID是惟一的,當咱們知道這個ID的時候,咱們能夠經過這個ID進行查詢

>>> post_id
ObjectId(...)
>>> pprint.pprint(posts.find_one({"_id": post_id}))
{u'_id': ObjectId('...'),
 u'author': u'Mike',
 u'date': datetime.datetime(...),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}

注意:上例中的ObjectID的數據類型並非str

>>> post_id_as_str = str(post_id)
>>> posts.find_one({"_id": post_id_as_str}) # No result
>>>

在網頁應用中,最多見的就是從request URL中或者ID並查詢,此時要注意的便是這個ID的數據類型問題了。

from bson.objectid import ObjectId

# The web framework gets post_id from the URL and passes it as a string
def get(post_id):
    # Convert from string to ObjectId:
    document = client.db.collection.find_one({'_id': ObjectId(post_id)})

 

多條數據插入

可使用insert_many()來插入多條數據。使用這種插入方法,並不須要多條命令。

>>> 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)}]
>>> result = posts.insert_many(new_posts)
>>> result.inserted_ids
[ObjectId('...'), ObjectId('...')]

注意:在第二條數據中,加入了一個與第一條數據格式不符合的數據點「title」,而數據庫不會發生錯誤,這也就是MongoDB的優勢之一:不會也別局限於數據點的格式。

 

多條數據查詢

可使用find()方法來查詢多條數據,返回的是一個Cursor實例,咱們能夠遍歷全部匹配的數據。

>>> for post in posts.find():
...   pprint.pprint(post)
...
{u'_id': ObjectId('...'),
 u'author': u'Mike',
 u'date': datetime.datetime(...),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}
{u'_id': ObjectId('...'),
 u'author': u'Mike',
 u'date': datetime.datetime(...),
 u'tags': [u'bulk', u'insert'],
 u'text': u'Another post!'}
{u'_id': ObjectId('...'),
 u'author': u'Eliot',
 u'date': datetime.datetime(...),
 u'text': u'and pretty easy too!',
 u'title': u'MongoDB is fun'}

一樣地,find()一樣支持條件查詢:

>>> for post in posts.find({"author": "Mike"}):
...   pprint.pprint(post)
...
{u'_id': ObjectId('...'),
 u'author': u'Mike',
 u'date': datetime.datetime(...),
 u'tags': [u'mongodb', u'python', u'pymongo'],
 u'text': u'My first blog post!'}
{u'_id': ObjectId('...'),
 u'author': u'Mike',
 u'date': datetime.datetime(...),
 u'tags': [u'bulk', u'insert'],
 u'text': u'Another post!'}

 

數據計數

當咱們只想知道有多少數據知足個人查詢條件的時候,可使用count()來對查詢結果計數。

>>> posts.count()
3
>>> posts.find({"author": "Mike"}).count()
2

 

範圍查詢

MongoDB一樣支持不少的高級查詢的功能,例如,咱們在下面的查詢中限定日期,並對查詢結果根據做者author進行排序:

>>> d = datetime.datetime(2009, 11, 12, 12)
>>> for post in posts.find({"date": {"$lt": d}}).sort("author"):
...   pprint.pprint(post)
...
{u'_id': ObjectId('...'),
 u'author': u'Eliot',
 u'date': datetime.datetime(...),
 u'text': u'and pretty easy too!',
 u'title': u'MongoDB is fun'}
{u'_id': ObjectId('...'),
 u'author': u'Mike',
 u'date': datetime.datetime(...),
 u'tags': [u'bulk', u'insert'],
 u'text': u'Another post!'}

 

索引

加入索引系統能夠加速查詢的進程而且添加更多的查詢功能。在這個例子中,咱們將要演示索引的建立以及使用:

首先,先建立一個索引

>>> result = db.profiles.create_index([('user_id', pymongo.ASCENDING)],
...                                   unique=True)
>>> sorted(list(db.profiles.index_information()))
[u'_id_', u'user_id_1']

在返回的結果中,有兩個ID,一個是MongoDB自動建立的,另外一個是咱們新加上去的。此時,咱們設置一些用戶ID:

>>> user_profiles = [
...     {'user_id': 211, 'name': 'Luke'},
...     {'user_id': 212, 'name': 'Ziltoid'}]
>>> result = db.profiles.insert_many(user_profiles)

然而索引系統就會自動地阻止咱們設置在Collection中重複的ID:

>>> new_profile = {'user_id': 213, 'name': 'Drew'}
>>> duplicate_profile = {'user_id': 212, 'name': 'Tommy'}
>>> result = db.profiles.insert_one(new_profile)  # This is fine.
>>> result = db.profiles.insert_one(duplicate_profile)
Traceback (most recent call last):
DuplicateKeyError: E11000 duplicate key error index: test_database.profiles.$user_id_1 dup key: { : 212 }
相關文章
相關標籤/搜索