libs:pymongo
python2.7.6
1、建立連接
#encoding=utf8 from pymongo import MongoClient url='mongodb://user_name:passwd@server_ip[:port]/datebase'#管理員要接入admin數據庫,由於mongoDB的驗證模式,其他數據庫可能無權限! con=MongoClient(url)
2、選擇DB並連接collection
db=con['datebase'] user=db.user #collection命名若有非法字符(‘-’等),報錯! user=db['user']
3、查詢【find or find_one】
user.find({'key':value}) #返回一個迭代器 user.find_one({'key':value}) #返回一個字典,僅匹配一個符合的記錄
4、複雜的查詢
db.order.find({'created_time':{'$gte':startTime,'$lte':endTime},'status':{'$in':status_paid}},{'items':1,'_id':0}) 查詢某個時間段,狀態在status_paid列表中;結果只要items的key——value對
經驗分享
pymongo是python庫,mongoDB的shell是javascript,一些語法不一樣(比如排序)
本機安裝mongoDB,命令行輸入mongo,進入javascript的shell
數據庫基本的操作:增刪改查
注意時間戳,javascript的時間戳是 【實際時間*1000】
漢字可直接錄入,編碼爲unicode,輸出(print or write)時要轉換爲utf8【name.encode('utf8')】
================
01 import pymongo
02 con = pymongo.Connection('localhost', 27017)
03 mydb = con.mydb # new a database
04 mydb.add_user('test', 'test') # add a user
05 mydb.authenticate('test', 'test') # check auth
06 muser = mydb.user # new a table
07
08 muser.save({'id':1, 'name':'test'}) # add a record
09 muser.insert({'id':2, 'name':'hello'}) # add a record
10 muser.find_one() # find a record
11 muser.find_one({'id':2}) # find a record by query
12
13 muser.create_index('id')
14 muser.find().sort('id', pymongo.ASCENDING) # DESCENDING
15 # muser.drop() delete table
16 muser.find({'id':1}).count() # get records number
17 muser.find({'id':1}).limit(3).skip(2) # start index is 2 limit 3 records
18 muser.remove({'id':1}) # delet records where id = 1
19
20 muser.update({'id':2}, {'$set':{'name':'haha'}}) # update one record
還有一些語法:
01 mongo –path
02 db.AddUser(username,password) 添加用戶
03 db.auth(usrename,password) 設置數據庫連接驗證
04 db.cloneDataBase(fromhost) 從目標服務器克隆一個數據庫
05 db.commandHelp(name) returns the help for the command
06 db.copyDatabase(fromdb,todb,fromhost) 複製數據庫fromdb—源數據庫名稱,todb—目標數據庫名稱,fromhost—源數據庫服務器地址
07 db.createCollection(name,{size:3333,capped:333,max:88888}) 創建一個數據集,相當於一個表
08 db.currentOp() 取消當前庫的當前操作
09 db.dropDataBase() 刪除當前數據庫
10 db.eval(func,args) run code server-side
11 db.getCollection(cname) 取得一個數據集合,同用法:db['cname'] or db.cname
12 db.getCollenctionNames() 取得所有數據集合的名稱列表
13 db.getLastError() 返回最後一個錯誤的提示消息
14 db.getLastErrorObj() 返回最後一個錯誤的對象
15 db.getMongo() 取得當前服務器的連接對象get the server connection object
16 db.getMondo().setSlaveOk() allow this connection to read from then nonmaster membr of a replica pair
17 db.getName() 返回當操作數據庫的名稱
18 db.getPrevError() 返回上一個錯誤對象
19 db.getProfilingLevel() ?什麼等級
20 db.getReplicationInfo() ?什麼信息
21 db.getSisterDB(name) get the db at the same server as this onew
22 db.killOp() 停止(殺死)在當前庫的當前操作
23 db.printCollectionStats() 返回當前庫的數據集狀態
24 db.printReplicationInfo()
25 db.printSlaveReplicationInfo()
26 db.printShardingStatus() 返回當前數據庫是否爲共享數據庫
27 db.removeUser(username) 刪除用戶
28 db.repairDatabase() 修復當前數據庫
29 db.resetError()
30 db.runCommand(cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj:1}
31 db.setProfilingLevel(level) 0=off,1=slow,2=all
32 db.shutdownServer() 關閉當前服務程序
33 db.version() 返回當前程序的版本信息
34
35 db.linlin.find({id:10}) 返回linlin數據集ID=10的數據集
36 db.linlin.find({id:10}).count() 返回linlin數據集ID=10的數據總數
37 db.linlin.find({id:10}).limit(2)返回linlin數據集ID=10的數據集從第二條開始的數據集
38 db.linlin.find({id:10}).skip(8) 返回linlin數據集ID=10的數據集從0到第八條的數據集
39 db.linlin.find({id:10}).limit(2).skip(8) 返回linlin數據集ID=1=的數據集從第二條到第八條的數據
40 db.linlin.find({id:10}).sort() 返回linlin數據集ID=10的排序數據集
41 db.linlin.findOne([query]) 返回符合條件的一條數據
42 db.linlin.getDB() 返回此數據集所屬的數據庫名稱
43 db.linlin.getIndexes() 返回些數據集的索引信息
44 db.linlin.group({key:…,initial:…,reduce:…[,cond:...]})
45 db.linlin.mapReduce(mayFunction,reduceFunction,
46 )
47 db.linlin.remove(query) 在數據集中刪除一條數據
48 db.linlin.renameCollection(newName) 重命名些數據集名稱
49 db.linlin.save(obj) 往數據集中插入一條數據
50 db.linlin.stats() 返回此數據集的狀態
51 db.linlin.storageSize() 返回此數據集的存儲大小
52 db.linlin.totalIndexSize() 返回此數據集的索引文件大小
53 db.linlin.totalSize() 返回些數據集的總大小
54 db.linlin.update(query,object[,upsert_bool])在此數據集中更新一條數據
55 db.linlin.validate() 驗證此數據集
56 db.linlin.getShardVersion() 返回數據集共享版本號
57 db.linlin.find({‘name’:'foobar’}) select * from linlin where name=’foobar’
58 db.linlin.find() select * from linlin
59 db.linlin.find({‘ID’:10}).count() select count(*) from linlin where ID=10
60 db.linlin.find().skip(10).limit(20) 從查詢結果的第十條開始讀20條數據 select *from linlin limit 10,20 ———-mysql
61 db.linlin.find({‘ID’:{$in:[25,35,45]}}) select * from linlin where ID in(25,35,45)
62 db.linlin.find().sort({‘ID’:-1}) select * from linlin order by ID desc
63 db.linlin.distinct(‘name’,{‘ID’:{$lt:20}}) select distinct(name) fromlinlin where ID<20
64 db.linlin.group({key:{'name':true},cond:{'name':'foo'},reduce:function(obj,prev){prev.msum+=obj.marks;},initial:{msum:0}})
65 select name,sum(marks) from linlin group by name
66 db.linlin.find('this.ID<20′,{name:1}) select name from linlin where ID<20
67 db.linlin.insert({'name':'foobar’,'age':25}) insert into linlin ('name','age’)values('foobar',25)
68 db.linlin.insert({'name':'foobar’,'age':25,’email’:'[email protected]’})
69 db.linlin.remove({}) delete * from linlin
70 db.linlin.remove({'age':20}) delete linlin where age=20
71 db.linlin.remove({'age':{$lt:20}}) delete linlin where age<20
72 db.linlin.remove({'age':{$lte:20}}) delete linlin where age<=20
73 db.linlin.remove({'age':{$gt:20}}) delete linlin where age>20
74 db.linlin.remove({‘age’:{$gte:20}}) delete linlin where age>=20
75 db.linlin.remove({‘age’:{$ne:20}}) delete linlin where age!=20
76 db.linlin.update({‘name’:'foobar’},{‘$set’:{‘age’:36}}) update linlinset age=36 where name=’foobar’
77 db.linlin.update({‘name’:'foobar’},{‘$inc’:{‘age’:3}}) update linlinset age=age+3 where name=’foobar’