這里是簡單的安裝和使用記錄,首先要有一個(gè)可用的mongo環(huán)境,win環(huán)境或者linux環(huán)境都可以。 假定你對mongo有所了解和知道一些命令行操作。
安裝和更新
跟大多數(shù)py包安裝一樣,可以源碼安裝,也可以使用pip或者easy_install來安裝
安裝
操作
小案例
from pymongo import MongoClient
def get_db():
#建立連接
client = MongoClient("localhost", 27017)
#test,還有其他寫法
db = client.test
return db
def get_collection(db):
#選擇集合(mongo中collection和database都是lazy創(chuàng)建的,具體可以google下)
collection = db['posts']
print collection
def insert_one_doc(db):
#插入一個(gè)document
posts = db.posts
post = {"name":"lzz", "age":25, "weight":"55"}
post_id = posts.insert(post)
print post_id
def insert_mulit_docs(db):
#批量插入documents,插入一個(gè)數(shù)組
posts = db.posts
post = [ {"name":"nine", "age":28, "weight":"55"},
{"name":"jack", "age":25, "weight":"55"}]
obj_ids = posts.insert(post)
print obj_ids
##查詢,可以對整個(gè)集合查詢,可以根ObjectId查詢,可以根據(jù)某個(gè)字段查詢等
def get_all_colls(db):
#獲得一個(gè)數(shù)據(jù)庫中的所有集合名稱
print db.collection_names()
def get_one_doc(db):
#有就返回一個(gè),沒有就返回None
posts = db.posts
print posts.find_one()
print posts.find_one({"name":"jack"})
print posts.find_one({"name":"None"})
return
def get_one_by_id(db):
#通過objectid來查找一個(gè)doc
posts = db.posts
obj = posts.find_one()
obj_id = obj["_id"]
print "_id 為ObjectId類型 :"
print posts.find_one({"_id":obj_id})
#需要注意這里的obj_id是一個(gè)對象,不是一個(gè)str,使用str類型作為_id的值無法找到記錄
print "_id 為str類型 "
print posts.find_one({"_id":str(obj_id)})
#可以通過ObjectId方法把str轉(zhuǎn)成ObjectId類型
from bson.objectid import ObjectId
print "_id 轉(zhuǎn)換成ObjectId類型"
print posts.find_one({"_id":ObjectId(str(obj_id))})
def get_many_docs(db):
#mongo中提供了過濾查找的方法,可以通過各
#種條件篩選來獲取數(shù)據(jù)集,還可以對數(shù)據(jù)進(jìn)行計(jì)數(shù),排序等處理
posts = db.posts
#所有數(shù)據(jù),按年齡排序, -1是倒序
all = posts.find().sort("age", -1)
count = posts.count()
print "集合中所有數(shù)據(jù) %s個(gè)"%int(count)
for i in all:
print i
#條件查詢
count = posts.find({"name":"lzz"}).count()
print "lzz: %s"%count
for i in posts.find({"name":"lzz", "age":{"$lt":20}}):
print i
def clear_coll_datas(db):
#清空一個(gè)集合中的所有數(shù)據(jù)
db.posts.remove({})
if __name__ == "__main__":
db = get_db()
obj_id = insert_one_doc(db)
obj_ids = insert_mulit_docs(db)
#get_all_colls(db)
#get_one_doc(db)
#get_one_by_id(db)
#get_many_docs(db)
clear_coll_datas(db)
新聞熱點(diǎn)
疑難解答
圖片精選