Mongodb的安裝及使用(一)
Mongodb 與 python 的交互(二)
mongodb數(shù)據(jù)庫備份和恢復(fù)(三)
1.Pymongo
PyMongo是Mongodb的Python接口開發(fā)包,是使用python和Mongodb的推薦方式。
官方文檔
2.安裝
進入虛擬環(huán)境
sudo pip install pymongo
或源碼安裝
python setup.py
3.使用
導(dǎo)入模塊
import pymongo
建立于MongoClient 的連接:
client = MongoClient('localhost', 27017)
# 或者
client = MongoClient('mongodb://localhost:27017/')
得到數(shù)據(jù)庫
db = client.test_database
# 或者
db = client['test-database']
得到一個數(shù)據(jù)集合
collection = db.test_collection
# 或者
collection = db['test-collection']
MongoDB中的數(shù)據(jù)使用的是類似Json風(fēng)格的文檔
>>> import datetime
>>> post = {"author": "Mike",
"text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.utcnow()}
插入一個文檔
>>> posts = db.posts
>>> post_id = posts.insert_one(post).inserted_id
>>> post_id
ObjectId('...')
查找一條數(shù)據(jù)
>>> 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']}
>>> posts.find_one({"author": "Mike"})
{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']}
>>> posts.find_one({"author": "Eliot"})
>>>
通過ObjectId來查找
>>> post_id ObjectId(...)
>>> posts.find_one({"_id": post_id})
{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']}
不要轉(zhuǎn)化ObjectId的類型為String
>>> post_id_as_str = str(post_id)
>>> posts.find_one({"_id": post_id_as_str}) # No result
>>>
如果post_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)})
多條插入
>>> 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('...')]
查找多條數(shù)據(jù)
>>> 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'}
#查找多個文檔2
cur=stu.find()
cur.next()
獲取集合的數(shù)據(jù)條數(shù)
posts.count()
#滿足某種查找條件的數(shù)據(jù)條數(shù):
posts.find({"author": "Mike"}).count()
范圍查找
#比如說時間范圍
>>> d = datetime.datetime(2009, 11, 12, 12)
>>> for post in posts.find({"date": {"$lt": d}}).sort("author"):
... print post
{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'}
{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']}
4.Mongodb與python交互列子
#-*- coding:utf-8 -*-
import pymongo
import datetime
def system():
print ('歡迎進入短文管理系統(tǒng)')
print ('1.增加信息')
print ('2.刪除信息')
print ('3.修改信息')
print ('4.查看數(shù)據(jù)')
print ('5.搜索信息')
print ('6.退出')
#建立與MongoClient的連接
client = pymongo.MongoClient('localhost',27017)
#創(chuàng)建并得到一個數(shù)據(jù)庫
db = client.test
#得到一個數(shù)據(jù)集合
msg = db.users
# msg.create_index([('time',pymongo.ASCENDING)],expireAfterSeconds=600)
while True:
order = int(raw_input('請輸入要進行的操作:'))
if order==1:
name = raw_input('請輸入短文標(biāo)題:')
desc = raw_input('請輸入內(nèi)容:')
data = {
"name":name,
"desc":desc,
"date":datetime.datetime.utcnow(),
}
msg.insert_one(data)
print ('添加成功')
elif order==2:
name = raw_input('請輸入你要刪除的短文:')
exit = msg.count({"name":name})
if exit!=0:
msg.remove({'name':name})
print ('刪除成功')
else:
print ('沒有此信息')
elif order==3:
name = raw_input('請輸入要修改的短文:')
exit = msg.count({"name":name})
if exit!=0:
desc = raw_input('請輸入內(nèi)容:')
msg.update({"name":name},{'$set':{'desc':desc}})
print ('修改成功')
else:
print ('你要修改的短文不存在')
elif order==4:
exit = msg.count({})
if exit==0:
print ('抱歉!還沒有數(shù)據(jù)')
else:
for data in msg.find():
content=data['name']+data['desc']
print content
elif order==5:
name = raw_input('請輸入你要查看的短文:')
exit = msg.count({'name':name})
if exit!=0:
data = msg.find_one({'name':name})
content = data['name']+data['desc']
else:
print ('你要查看的短文不存在')
elif order==6:
print ('感謝使用')
break
else:
print ('請輸入1/2/3/4/5/6相關(guān)指令')
if __name__=='__main__':
system()