Mongo_mysql_Dif

mysql 和 mongo db 語法對比


http://blog.zhangwenjin.com/?p=139
本文描述了MySQL中的常用SQL語句在MongoDB中的寫法,如果你長期使用MySQL而對MongoDB躍躍欲試,這篇簡單的文章可以幫助你更快的進入角色。
查詢:
MySQL:
SELECT * FROM user
Mongo:
db.user.find()
MySQL:
SELECT * FROM user WHERE name = ’starlee’
Mongo:
db.user.find({‘name’ : ’starlee’})
插入:
MySQL:
INSERT INOT user (`name`, `age`) values (’starlee’,25)
Mongo:
db.user.insert({‘name’ : ’starlee’, ‘age’ : 25})
如果你想在MySQL裏添加一個字段,你必須:
ALTER TABLE user….
但在MongoDB裏你只需要:
db.user.insert({‘name’ : ’starlee’, ‘age’ : 25, ‘email’ : [email protected]})
刪除:
MySQL:
DELETE * FROM user
Mongo:
db.user.remove({})
MySQL:
DELETE FROM user WHERE age < 30
Mongo:
db.user.remove({‘age’ : {$lt : 30}})
$gt : > ; $gte : >= ; $lt : < ; $lte : <= ; $ne : !=
更新:
MySQL:
UPDATE user SET `age` = 36 WHERE `name` = ’starlee’
Mongo:
db.user.update({‘name’ : ’starlee’}, {$set : {‘age’ : 36}})
MySQL:
UPDATE user SET `age` = `age` + 3 WHERE `name` = ’starlee’
Mongo:
db.user.update({‘name’ : ’starlee’}, {$inc : {‘age’ : 3}})
MySQL:
SELECT COUNT(*) FROM user WHERE `name` = ’starlee’
Mongo:
db.user.find({‘name’ : ’starlee’}).count()
MySQL:
SELECT * FROM user limit 10,20
Mongo:
db.user.find().skip(10).limit(20)
MySQL:
SELECT * FROM user WHERE `age` IN (25, 35,45)
Mongo:
db.user.find({‘age’ : {$in : [25, 35, 45]}})
MySQL:
SELECT * FROM user ORDER BY age DESC
Mongo:
db.user.find().sort({‘age’ : -1})
MySQL:
SELECT DISTINCT(name) FROM user WHERE age > 20
Mongo:
db.user.distinct(‘name’, {‘age’: {$lt : 20}})
MySQL:
SELECT name, sum(marks) FROM user GROUP BY name
Mongo:
db.user.group({
key : {‘name’ : true},
cond: {‘name’ : ‘foo’},
reduce: function(obj,prev) { prev.msum += obj.marks; },
initial: {msum : 0}
});
MySQL:
SELECT name FROM user WHERE age < 20
Mongo:
db.user.find(‘this.age < 20′, {name : 1})
發現很多人在搜MongoDB循環插入數據,下面把MongoDB循環插入數據的方法添加在下面:
for(var i=0;i<100;i++)db.test.insert({uid:i,uname:’nosqlfan’+i});
上面一次性插入一百條數據,大概結構如下:
{ “_id” : ObjectId(“4c876e519e86023a30dde6b8″), “uid” : 55, “uname” : “nosqlfan55″ }
{ “_id” : ObjectId(“4c876e519e86023a30dde6b9″), “uid” : 56, “uname” : “nosqlfan56″ }
{ “_id” : ObjectId(“4c876e519e86023a30dde6ba”), “uid” : 57, “uname” : “nosqlfan57″ }
{ “_id” : ObjectId(“4c876e519e86023a30dde6bb”), “uid” : 58, “uname” : “nosqlfan58″ }
{ “_id” : ObjectId(“4c876e519e86023a30dde6bc”), “uid” : 59, “uname” : “nosqlfan59″ }
{ “_id” : ObjectId(“4c876e519e86023a30dde6bd”), “uid” : 60, “uname” : “nosqlfan60″ }
php 下推薦的mongo 客戶端: http://code.google.com/p/rock-php/
mongo語法
http://wangjc-opal.javaeye.com/blog/802571
啓動服務
mongod.exe --dbpath D:/MongoDB/mongodbwin321.6.0/data
--dbpath 數據文件存放路徑
--port 數據服務端口
啓動客戶端
mongo.exe cclove
cclove  所連接的數據庫名稱
數據庫操作語法
mongo --path
db.AddUser(username,password)  添加用戶
db.auth(usrename,password)  設置數據庫連接驗證
db.cloneDataBase(fromhost)  從目標服務器克隆一個數據庫
db.commandHelp(name)     returns the help for the command
db.copyDatabase(fromdb,todb,fromhost)  複製數據庫fromdb---源數據庫名稱,todb---目標數據庫名稱,fromhost---源數據庫服務器地址
db.createCollection(name,{size:3333,capped:333,max:88888})  創建一個數據集,相當於一個表
db.currentOp()     取消當前庫的當前操作
db.dropDataBase()     刪除當前數據庫
db.eval(func,args)    run code server-side
db.getCollection(cname)  取得一個數據集合,同用法:db['cname'] or db.cname
db.getCollenctionNames()    取得所有數據集合的名稱列表
db.getLastError()     返回最後一個錯誤的提示消息
db.getLastErrorObj()     返回最後一個錯誤的對象
db.getMongo()      取得當前服務器的連接對象get the server connection object
db.getMondo().setSlaveOk()  allow this connection to read from then nonmaster membr of a replica pair
db.getName()       返回當操作數據庫的名稱
db.getPrevError()     返回上一個錯誤對象
db.getProfilingLevel()   ?什麼等級
db.getReplicationInfo()  ?什麼信息
db.getSisterDB(name)     get the db at the same server as this onew
db.killOp()     停止(殺死)在當前庫的當前操作
db.printCollectionStats()   返回當前庫的數據集狀態
db.printReplicationInfo()
db.printSlaveReplicationInfo()
db.printShardingStatus()    返回當前數據庫是否爲共享數據庫
db.removeUser(username)  刪除用戶
db.repairDatabase()   修復當前數據庫
db.resetError()
db.runCommand(cmdObj)    run a database command. if cmdObj is a string, turns it into {cmdObj:1}
db.setProfilingLevel(level) 0=off,1=slow,2=all
db.shutdownServer()   關閉當前服務程序
db.version()       返回當前程序的版本信息
數據集(表)操作語法
db.linlin.find({id:10})    返回linlin數據集ID=10的數據集
db.linlin.find({id:10}).count()  返回linlin數據集ID=10的數據總數
db.linlin.find({id:10}).limit(2) 返回linlin數據集ID=10的數據集從第二條開始的數據集
db.linlin.find({id:10}).skip(8)  返回linlin數據集ID=10的數據集從0到第八條的數據集
db.linlin.find({id:10}).limit(2).skip(8)  返回linlin數據集ID=1=的數據集從第二條到第八條的數據
db.linlin.find({id:10}).sort()   返回linlin數據集ID=10的排序數據集
db.linlin.findOne([query])    返回符合條件的一條數據
db.linlin.getDB()    返回此數據集所屬的數據庫名稱
db.linlin.getIndexes()     返回些數據集的索引信息
db.linlin.group({key:...,initial:...,reduce:...[,cond:...]})
db.linlin.mapReduce(mayFunction,reduceFunction,<optional params>)
db.linlin.remove(query)       在數據集中刪除一條數據
db.linlin.renameCollection(newName)    重命名些數據集名稱
db.linlin.save(obj)        往數據集中插入一條數據
db.linlin.stats()       返回此數據集的狀態
db.linlin.storageSize()       返回此數據集的存儲大小
db.linlin.totalIndexSize()       返回此數據集的索引文件大小
db.linlin.totalSize()      返回些數據集的總大小
db.linlin.update(query,object[,upsert_bool]) 在此數據集中更新一條數據
db.linlin.validate()       驗證此數據集
db.linlin.getShardVersion()      返回數據集共享版本號
db.linlin.find({'name':'foobar'}) select * from linlin where name='foobar'
db.linlin.find()      select * from linlin
db.linlin.find({'ID':10}).count() select count(*) from linlin where ID=10
db.linlin.find().skip(10).limit(20)  從查詢結果的第十條開始讀20條數據  select * from linlin limit 10,20  ----------mysql
db.linlin.find({'ID':{$in:[25,35,45]}})  select * from linlin where ID in (25,35,45)
db.linlin.find().sort({'ID':-1})   select * from linlin order by ID desc
db.linlin.distinct('name',{'ID':{$lt:20}})   select distinct(name) from linlin where ID<20
db.linlin.group({key:{'name':true},cond:{'name':'foo'},reduce:function(obj,prev){prev.msum+=obj.marks;},initial:{msum:0}})
select name,sum(marks) from linlin group by name
db.linlin.find('this.ID<20',{name:1})  select name from linlin where ID<20
db.linlin.insert({'name':'foobar','age':25})  insert into linlin ('name','age') values('foobar',25)
db.linlin.insert({'name':'foobar','age':25,'email':'[email protected]'})
db.linlin.remove({})       delete * from linlin
db.linlin.remove({'age':20})     delete linlin where age=20
db.linlin.remove({'age':{$lt:20}})  delete linlin where age<20
db.linlin.remove({'age':{$lte:20}}) delete linlin where age<=20
db.linlin.remove({'age':{$gt:20}})  delete linlin where age>20
db.linlin.remove({'age':{$gte:20}}) delete linlin where age>=20
db.linlin.remove({'age':{$ne:20}})  delete linlin where age!=20
db.linlin.update({'name':'foobar'},{$set:{'age':36}})  update linlin set age=36 where name='foobar'
db.linlin.update({'name':'foobar'},{$inc:{'age':3}})   update linlin set age=age+3 where name='foobar'
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/firetaker/archive/2010/08/12/5806628.aspx
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
MongoDB的好處挺多的,比如多列索引,查詢時可以用一些統計函數,支持多條件查詢,但是目前多表查詢是不支持的,可以想辦法通過數據冗餘來解決多表 查詢的問題。
MongoDB對數據的操作很豐富,下面做一些舉例說明,內容大部分來自官方文檔,另外有部分爲自己理解。
查詢colls所有數據
db.colls.find() //select * from colls
通過指定條件查詢
db.colls.find({'last_name': 'Smith'});//select * from colls where last_name='Smith'
指定多條件查詢
db.colls.find( { x : 3, y : "foo" } );//select * from colls where x=3 and y='foo'
指定條件範圍查詢
db.colls.find({j: {$ne: 3}, k: {$gt: 10} });//select * from colls where j!=3 and k>10
查詢不包括某內容
db.colls.find({}, {a:0});//查詢除a爲0外的所有數據
支持<, <=, >, >=查詢,需用符號替代分別爲$lt,$lte,$gt,$gte
db.colls.find({ "field" : { $gt: value } } );
db.colls.find({ "field" : { $lt: value } } );
db.colls.find({ "field" : { $gte: value } } );
db.colls.find({ "field" : { $lte: value } } );
也可對某一字段做範圍查詢
db.colls.find({ "field" : { $gt: value1, $lt: value2 } } );
不等於查詢用字符$ne
db.colls.find( { x : { $ne : 3 } } );
in查詢用字符$in
db.colls.find( { "field" : { $in : array } } );
db.colls.find({j:{$in: [2,4,6]}});
not in查詢用字符$nin
db.colls.find({j:{$nin: [2,4,6]}});
取模查詢用字符$mod
db.colls.find( { a : { $mod : [ 10 , 1 ] } } )// where a % 10 == 1
$all查詢
db.colls.find( { a: { $all: [ 2, 3 ] } } );//指定a滿足數組中任意值時
$size查詢
db.colls.find( { a : { $size: 1 } } );//對對象的數量查詢,此查詢查詢a的子對象數目爲1的記錄
$exists查詢
db.colls.find( { a : { $exists : true } } ); // 存在a對象的數據
db.colls.find( { a : { $exists : false } } ); // 不存在a對象的數據
$type查詢$type值爲bsonhttp://bsonspec.org/數 據的類型值
db.colls.find( { a : { $type : 2 } } ); // 匹配a爲string類型數據
db.colls.find( { a : { $type : 16 } } ); // 匹配a爲int類型數據
使用正則表達式匹配
db.colls.find( { name : /acme.*corp/i } );//類似於SQL中like
內嵌對象查詢
db.colls.find( { "author.name" : "joe" } );
1.3.3版本及更高版本包含$not查詢
db.colls.find( { name : { $not : /acme.*corp/i } } );
db.colls.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
sort()排序
db.colls.find().sort( { ts : -1 } );//1爲升序2爲降序
limit()對限制查詢數據返回個數
db.colls.find().limit(10)
skip()跳過某些數據
db.colls.find().skip(10)
snapshot()快照保證沒有重複數據返回或對象丟失
count()統計查詢對象個數
db.students.find({'address.state' : 'CA'}).count();//效率較高
db.students.find({'address.state' : 'CA'}).toArray().length;//效率很低
group()對查詢結果分組和SQL中group by函數類似
distinct()返回不重複值
/***************************************************************************/
時間檢索
//檢索 7月12 到 8月1號的數據
db.cpc_common.cpc_click_detail_log.count({date_created:{$gte:new Date(2010, 6,12), $lt:new Date(2010,7,1)}})
//刪除 7月12 到 8月1號的數據
 db.cpc_common.cpc_click_detail_log.remove({date_created:{$gte:new Date(2010, 6,12), $lt:new Date(2010,7,1)}})

 

發佈了8 篇原創文章 · 獲贊 3 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章