mongoDB的各种查询语句全⾯易懂!!
⽰例
左边是mongodb查询语句,右边是sql语句。对照着⽤,挺⽅便。
db.urs.find()lect*from urs
db.urs.find({"age" : 27})lect*from urs where age =27
db.urs.find({"urname" : "joe","age" : 27})lect*from urs where"urname"="joe"and age =27
db.urs.find({}, {"urname" : 1,"email" : 1})lect urname, email from urs
db.urs.find({}, {"urname" : 1,"_id" : 0})// no ca // 即时加上了列筛选,_id也会返回;必须显式的阻⽌_id返回
db.urs.find({"age" : {"$gte" : 18,"$lte" : 30}})lect*from urs where age >=18and age <=30// $lt(<) $lte(<=) $gt(>) $gte(>=)
db.urs.find({"urname" : {"$ne" : "joe"}})lect*from urs where urname <>"joe"
db.urs.find({"ticket_no" : {"$in" : [725,542,390]}})lect*from urs where ticket_no in(725,542,390)
db.urs.find({"ticket_no" : {"$nin" : [725,542,390]}})lect*from urs where ticket_no not in(725,542,390)
db.urs.find({"$or" : [{"ticket_no" : 725}, {"winner" : true}]})lect* form urs where ticket_no =725or winner =true
db.urs.find({"id_num" : {"$mod" : [5,1]}})lect*from urs where(id_num mod 5)=1
db.urs.find({"$not": {"age" : 27}})lect*from urs where not(age =27)
db.urs.find({"urname" : {"$in" : [null],"$exists" : true}})lect*from urs where urname is null// 如果直接通过find({"urname" : null})进⾏查询,那么连带"没有urname"的纪录⼀并筛选出来
db.urs.find({"name" : /joey?/i})// 正则查询,value是符合PCRE的表达式
db.food.find({fruit : {$all : ["apple","banana"]}})// 对数组的查询, 字段fruit中,既包含"apple",⼜包含"banana"的纪录
db.food.find({"fruit.2" : "peach"})// 对数组的查询, 字段fruit中,第3个(从0开始)元素是peach的纪录
db.food.find({"fruit" : {"$size" : 3}})// 对数组的查询, 查询数组元素个数是3的记录,$size前⾯⽆法和其他的操作符复合使⽤
db.urs.findOne(criteria, {"comments" : {"$slice" : 10}})// 对数组的查询,只返回数组comments中的前⼗条,还可以{"$slice" : -10}, {"$slice" : [23, 10]}; 分别返回最后10条,和中间10条
db.people.find({"name.first" : "Joe","name.last" : "Schmoe"})// 嵌套查询
告诫自己该清醒的句子db.blog.find({"comments" : {"$elemMatch" : {"author" : "joe","score" : {"$gte" : 5}}}})// 嵌套查询,仅当嵌套的元素是数组时使⽤,
db.foo.find({"$where" : "this.x + this.y == 10"})// 复杂的查询,$where当然是⾮常⽅便的,但效率低下。对于复杂查询,考虑的顺序应当是正则 -> MapReduc e -> $where
db.foo.find({"$where" : "function() { return this.x + this.y == 10; }"})// $where可以⽀持javascript函数作为查询条件
db.foo.find().sort({"x" : 1}).limit(1).skip(10);// 返回第(10, 11]条,按"x"进⾏排序; 三个limit的顺序是任意的,应该尽量避免skip中使⽤large-number
projection应⽤:
冬奥会项目
人参禁忌db.urs.find({},{projection})
(注意:filter实现的是筛选出某条数据,projection实现的是筛选出某条数据的具体字段)
筛选含age字段的数据并显⽰(只显⽰age字段):
db.urs.find({},{_id:1,age:1})
//age:0 则为反选,或者⽤true/fal也⼀样
详见官⽅的⼿册:
1).⼤于,⼩于,⼤于或等于,⼩于或等于
$gt:⼤于
$lt:⼩于
$gte:⼤于或等于
$lte:⼩于或等于
例⼦:规章制度
如查询j⼤于3,⼩于4:
db.things.find({j : {$lt: 3}});
db.things.find({j : {$gte: 4}});
也可以合并在⼀条语句内:
2)不等于 $ne
例⼦:
db.things.find( { x : { $ne : 3 } } );
3)in和not in($in $nin)
语法:
交通安全标识例⼦:
db.things.find({j:{$in: [2,4,6]}});
db.things.find({j:{$nin: [2,4,6]}});
4)取模运算$mod
如下⾯的运算:
db.things.find("this.a % 10 == 1")
可⽤$mod代替:
db.things.find( { a : { $mod : [10,1] } } )
5) $all
$all和$in类似,但是他需要匹配条件内所有的值:
如有⼀个对象:
{ a: [1,2,3] }
下⾯这个条件是可以匹配的:
db.things.find( { a: { $all: [2,3] } } );
db.things.find( { a: { $all: [2,3] } } );
但是下⾯这个条件就不⾏了:
db.things.find( { a: { $all: [2,3,4] } } );
6) $size
$size是匹配数组内的元素数量的,如有⼀个对象:{a:["foo"]},他只有⼀个元素:
临沂科技学校下⾯的语句就可以匹配:
db.things.find( { a : { $size: 1 } } );
官⽹上说不能⽤来匹配⼀个范围内的元素,如果想找$size<5之类的,他们建议创建⼀个字段来保存元素的数量。
You cannot u $size to find a range of sizes (for example: arrays with more than 1 element).If you need to query for a range,create an extra size field th at you increment when you add elements.
7)$exists
$exists⽤来判断⼀个元素是否存在:
如:
db.things.find( { a : { $exists : true } } );// 如果存在元素a,就返回
db.things.find( { a : { $exists : fal } } );// 如果不存在元素a,就返回
8) $type
$type基于 bson type来匹配⼀个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
db.things.find( { a : { $type : 2 } } );// matches if a is a string
db.things.find( { a : { $type : 16 } } );// matches if a is an int
9)正则表达式
mongo⽀持正则表达式,如:
db.customers.find( { name : /acme.*corp/i } );// 后⾯的i的意思是区分⼤⼩写
10)查询数据内的值
下⾯的查询是查询colors内red的记录,如果colors元素是⼀个数据,数据库将遍历这个数组的元素来查询。
db.things.find( { colors : "red" } );清纯美女壁纸
11) $elemMatch
如果对象有⼀个元素是数组,那么$elemMatch可以匹配内数组内的元素:
> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
{ "_id" : ObjectId("4b5783300334000000000aa9"),
"x" : [ { "a" : 1,"b" : 3 },7, { "b" : 99 }, { "a" : 11 } ]
}
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才⾏。
注意,上⾯的语句和下⾯是不⼀样的。
> t.find( { "x.a" : 1,"x.b" : { $gt : 1 } } )
$elemMatch是匹配{ "a" : 1,"b" : 3 },⽽后⾯⼀句是匹配{ "b" : 99 }, { "a" : 11 }
12)查询嵌⼊对象的值
db.postings.find( { "author.name" : "joe" } );
注意⽤法是author.name,⽤⼀个点就⾏了。更详细的可以看这个链接: dot notation
举个例⼦:
> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
如果我们要查询 authors name 是Jane的,我们可以这样:
如果我们要查询 authors name 是Jane的,我们可以这样:
> db.blog.findOne({"author.name" : "Jane"})
如果不⽤点,那就需要⽤下⾯这句才能匹配:
db.blog.findOne({"author" : {"name" : "Jane","id" : 1}})
下⾯这句:
db.blog.findOne({"author" : {"name" : "Jane"}})
是不能匹配的,因为mongodb对于⼦对象,他是精确匹配。
13)元操作符 $not取反
如:
db.customers.find( { name : { $not : /acme.*corp/i } } );
db.things.find( { a : { $not : { $mod : [10,1] } } } );
mongodb还有很多函数可以⽤,如排序,统计等,请参考原⽂。
mongodb⽬前没有或(or)操作符,只能⽤变通的办法代替,可以参考下⾯的链接:db/display/DOCS/OR+operations+in+query+expressions 版本⼆:
shell 环境下的操作:
1.超级⽤户相关:
1.#进⼊数据库admin
u admin
2.#增加或修改⽤户密码
db.addUr('name','pwd')
3.#查看⽤户列表
db.system.urs.find()
4.#⽤户认证
db.auth('name','pwd')
5.#删除⽤户
6.#查看所有⽤户
show urs
7.#查看所有数据库
show dbs
8.#查看所有的collection
show collections
9.#查看各collection的状态
db.printCollectionStats()
10.#查看主从复制状态
db.printReplicationInfo()
11.#修复数据库
12.#设置记录profiling,0=off 1=slow 2=all
db.tProfilingLevel(1)
13.#查看profiling
show profile
14.#拷贝数据库
15.#删除collection
db.mail_addr.drop()
尽心尽责16.#删除当前的数据库
db.dropDataba()
2.增删改
1.#存储嵌套的对象
db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
2.#存储数组对象
db.ur_addr.save({'Uid':'','Al':['','']})
3.#根据query条件修改,如果不存在则插⼊,允许修改多条记录
db.foo.update({'yy':5},{'$t':{'xx':2}},uprt=true,multi=true)
4.#删除yy=5的记录
ve({'yy':5})
5.#删除所有的记录
ve()
3.索引
1.#增加索引:1(ascending),-1(descending)
2. sureIndex({firstname: 1, lastname: 1}, {unique: true});
3.#索引⼦对象
4. db.sureIndex({'Al.Em': 1})
5.#查看索引信息
6. Indexes()