下載python中MongoDB的驅動程序python
pip install pymongo
而後確保MongoDB已經安裝且能夠正常運行,去官網下載相應版本:https://www.mongodb.com/linux
mkdir -p /home/tools cd/home/tools wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.4.2.tgz
解壓文件並修改目錄名mongodb
tar -zxvf mongodb-linux-x86_64-3.4.2.tgz mv mongodb-linux-x86_64-3.4.2 mongodb3.4.2
ln -s mongodb_3.4.2 mongodb
MongoDB 的可執行文件位於 bin 目錄下,因此能夠將其添加到 PATH 路徑中shell
export PATH=/home/tools/mongodb/bin:$PATH
MongoDB的數據存儲在data目錄的db目錄下,可是這個目錄在安裝過程不會自動建立,因此你須要手動建立data目錄,並在data目錄中建立db目錄。數據庫
mkdir -p /data/db
在mongo安裝目錄中的bin目錄執行mongod命令來啓動mongdb服務數組
./mongod --dbpath /data/db
若是想進入MongoDB後臺管理iphone
./mongo
# ./mongo MongoDB shell version v3.4.2 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.2 Welcome to the MongoDB shell. ..................... times number of files. 2017-03-12T01:15:04.901+0800 I CONTROL [initandlisten] >
使用用戶 admin 使用密碼 123456 鏈接到本地的 MongoDB 服務上ide
> mongodb://admin:123456@localhost/
...
建立數據庫(若是數據庫不存在,則建立數據庫,不然切換到指定數據庫)spa
... use test
2017-03-12T01:34:04.361+0800 E QUERY [thread1] SyntaxError: missing ; before statement @(shell):3:4
> use test switched to db test > db test > show dbs #查看全部數據庫 admin 0.000GB local 0.000GB
python操做mongodb3d
鏈接mongodb
#!/usr/bin/env python # -*- coding:utf-8 -*- from pymongo import MongoClient conn = MongoClient('192.168.0.113', 27017) db = conn.mydb #鏈接mydb數據庫,沒有則自動建立 my_set = db.test_set #使用test_set集合,沒有則自動建立
插入數據(insert插入一個列表多條數據不用遍歷,效率高, save須要遍歷列表,一個個插入)
my_set.insert({"name":"zhangsan","age":18}) #或 my_set.save({"name":"zhangsan","age":18})
插入多條
#添加多條數據到集合中 users=[{"name":"zhangsan","age":18},{"name":"lisi","age":20}] my_set.insert(users) #或 my_set.save(users)
查詢數據(查詢不到則返回None)
#查詢所有 for i in my_set.find(): print(i) #查詢name=zhangsan的 for i in my_set.find({"name":"zhangsan"}): print(i) print(my_set.find_one({"name":"zhangsan"}))
更新數據
my_set.update( <query>, #查詢條件 <update>, #update的對象和一些更新的操做符 { upsert: <boolean>, #若是不存在update的記錄,是否插入 multi: <boolean>, #可選,mongodb 默認是false,只更新找到的第一條記錄 writeConcern: <document> #可選,拋出異常的級別。 } )
把上面插入的數據內的age改成20
my_set.update({"name":"zhangsan"},{'$set':{"age":20}})
刪除數據
my_set.remove( <query>, #(可選)刪除的文檔的條件 { justOne: <boolean>, #(可選)若是設爲 true 或 1,則只刪除一個文檔 writeConcern: <document> #(可選)拋出異常的級別 } )
#刪除name=lisi的所有記錄 my_set.remove({'name': 'zhangsan'}) #刪除name=lisi的某個id的記錄 id = my_set.find_one({"name":"zhangsan"})["_id"] my_set.remove(id) #刪除集合裏的全部記錄 db.users.remove()
mongodb的條件操做符
# (>) 大於 - $gt # (<) 小於 - $lt # (>=) 大於等於 - $gte # (<= ) 小於等於 - $lte
#例:查詢集合中age大於25的全部記錄 for i in my_set.find({"age":{"$gt":25}}): print(i)
type(判斷類型)
#找出name的類型是String的 for i in my_set.find({'name':{'$type':2}}): print(i)
類型隊對照列表
Double 1 String 2 Object 3 Array 4 Binary data 5 Undefined 6 已廢棄 Object id 7 Boolean 8 Date 9 Null 10 Regular Expression 11 JavaScript 13 Symbol 14 JavaScript (with scope) 15 32-bit integer 16 Timestamp 17 64-bit integer 18 Min key 255 Query with -1. Max key 127
排序
在MongoDB中使用sort()方法對數據進行排序,sort()方法能夠經過參數指定排序的字段,並使用 1 和 -1 來指定排序的方式,其中 1 爲升序,-1爲降序。
for i in my_set.find().sort([("age",1)]): print(i)
limit和skip
#limit()方法用來讀取指定數量的數據 #skip()方法用來跳過指定數量的數據 #下面表示跳過兩條數據後讀取6條 for i in my_set.find().skip(2).limit(6): print(i)
IN
#找出age是20、30、35的數據 for i in my_set.find({"age":{"$in":(20,30,35)}}): print(i)
OR
#找出age是20或35的記錄 for i in my_set.find({"$or":[{"age":20},{"age":35}]}): print(i)
all
''' dic = {"name":"lisi","age":18,"li":[1,2,3]} dic2 = {"name":"zhangsan","age":18,"li":[1,2,3,4,5,6]} my_set.insert(dic) my_set.insert(dic2)''' for i in my_set.find({'li':{'$all':[1,2,3,4]}}): print(i) #查看是否包含所有條件 #輸出:{'_id': ObjectId('58c503b94fc9d44624f7b108'), 'name': 'zhangsan', 'age': 18, 'li': [1, 2, 3, 4, 5, 6]}
push/pushAll
my_set.update({'name':"lisi"}, {'$push':{'li':4}}) for i in my_set.find({'name':"lisi"}): print(i) #輸出:{'li': [1, 2, 3, 4], '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi'} my_set.update({'name':"lisi"}, {'$pushAll':{'li':[4,5]}}) for i in my_set.find({'name':"lisi"}): print(i) #輸出:{'li': [1, 2, 3, 4, 4, 5], 'name': 'lisi', 'age': 18, '_id': ObjectId('58c50d784fc9d44ad8f2e803')}
pop/pull/pullAll
#pop #移除最後一個元素(-1爲移除第一個) my_set.update({'name':"lisi"}, {'$pop':{'li':1}}) for i in my_set.find({'name':"lisi"}): print(i) #輸出:{'_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi', 'li': [1, 2, 3, 4, 4]} #pull (按值移除) #移除3 my_set.update({'name':"lisi"}, {'$pop':{'li':3}}) #pullAll (移除所有符合條件的) my_set.update({'name':"lisi"}, {'$pullAll':{'li':[1,2,3]}}) for i in my_set.find({'name':"lisi"}): print(i) #輸出:{'name': 'lisi', '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'li': [4, 4], 'age': 18}
多級路徑元素操做
先插入一條數據
dic = {"name":"zhangsan", "age":18, "contact" : { "email" : "1234567@qq.com", "iphone" : "11223344"} } my_set.insert(dic)
#多級目錄用. 鏈接 for i in my_set.find({"contact.iphone":"11223344"}): print(i) #輸出:{'name': 'zhangsan', '_id': ObjectId('58c4f99c4fc9d42e0022c3b6'), 'age': 18, 'contact': {'email': '1234567@qq.com', 'iphone': '11223344'}} result = my_set.find_one({"contact.iphone":"11223344"}) print(result["contact"]["email"]) #輸出:1234567@qq.com #多級路徑下修改操做 result = my_set.update({"contact.iphone":"11223344"},{"$set":{"contact.email":"9999999@qq.com"}}) result1 = my_set.find_one({"contact.iphone":"11223344"}) print(result1["contact"]["email"]) #輸出:9999999@qq.com
還能夠對數組用索引操做
dic = {"name":"lisi", "age":18, "contact" : [ { "email" : "111111@qq.com", "iphone" : "111"}, { "email" : "222222@qq.com", "iphone" : "222"} ]} my_set.insert(dic)
#查詢 result1 = my_set.find_one({"contact.1.iphone":"222"}) print(result1) #輸出:{'age': 18, '_id': ObjectId('58c4ff574fc9d43844423db2'), 'name': 'lisi', 'contact': [{'iphone': '111', 'email': '111111@qq.com'}, {'iphone': '222', 'email': '222222@qq.com'}]} #修改 result = my_set.update({"contact.1.iphone":"222"},{"$set":{"contact.1.email":"222222@qq.com"}}) print(result1["contact"][1]["email"]) #輸出:222222@qq.com
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 from pymongo import MongoClient 4 5 settings = { 6 "ip":'192.168.0.113', #ip 7 "port":27017, #端口 8 "db_name" : "mydb", #數據庫名字 9 "set_name" : "test_set" #集合名字 10 } 11 12 class MyMongoDB(object): 13 def __init__(self): 14 try: 15 self.conn = MongoClient(settings["ip"], settings["port"]) 16 except Exception as e: 17 print(e) 18 self.db = self.conn[settings["db_name"]] 19 self.my_set = self.db[settings["set_name"]] 20 21 def insert(self,dic): 22 print("inser...") 23 self.my_set.insert(dic) 24 25 def update(self,dic,newdic): 26 print("update...") 27 self.my_set.update(dic,newdic) 28 29 def delete(self,dic): 30 print("delete...") 31 self.my_set.remove(dic) 32 33 def dbfind(self,dic): 34 print("find...") 35 data = self.my_set.find(dic) 36 for result in data: 37 print(result["name"],result["age"]) 38 39 def main(): 40 dic={"name":"zhangsan","age":18} 41 mongo = MyMongoDB() 42 mongo.insert(dic) 43 mongo.dbfind({"name":"zhangsan"}) 44 45 mongo.update({"name":"zhangsan"},{"$set":{"age":"25"}}) 46 mongo.dbfind({"name":"zhangsan"}) 47 48 mongo.delete({"name":"zhangsan"}) 49 mongo.dbfind({"name":"zhangsan"}) 50 51 if __name__ == "__main__": 52 main()