一、高级查询
原型:
db.foo.find( query , fields,limit,skip)
第一个参数是一个可选的查询过滤器,第二个参数要返回的字段的集合,第三个参数是限制返回的文档数,第四个参数是指跳过的文档数。
实验数据:
1.1、条件操作符(=($gte))
查询编号大于2的学生信息( db.scores.find({"num":{$gt:2}}))。
1.2、and查询($and):并且
查询编号大于2且小于等于5的学生信息db.scores.find({$and:[{"num":{$gt:2}},{"num":{$lte:5}}]}) 。
也可以这样操作(db.scores.find({"num":{$gt:2,$lte:5}}))。
1.3、or查询($or):或者
查询编号小于等于2或者编号大于5的学生的信息(db.scores.find({$or:[{"num":{$lte:2}},{"num":{$gt:5}}]}))。
1.4、nor查询($nor):既不也不
查询编号既不小于2也不大于等于5的学生信息(db.scores.find({$nor:[{"num":{$lt:2}},{"num":{$gte:5}}]}))。
1.5、in查询($in):匹配列表中的某一个
查询编号匹配1,4,6中某一个的学生信息(db.scores.find({"num":{$in:[1,4,6]}}))。
1.6、nin查询($nin):不匹配列表中的全部(任意一个)
查询编号不在1,4,6中的学生的信息(db.scores.find({"num":{$nin:[1,4,6]}}))。
1.7、all查询($all):匹配所有
添加两条测试数据:{"num" : 7, "name" : "7号", "score" : { "math" : 45, "chinese" : 56, "english" : 78 }, "hobby" : [ "music", "read", "footbal" ] }
{"num" : 8, "name" : "8号", "score" : { "math" : 47, "chinese" : 66, "english" : 68 }, "hobby" : [ "music", "read", "swimming" ] }
查询爱好有音乐和游泳的学生的信息,为方便观察,我们指定返回的列:db.scores.find({"hobby":{$all:["music","swimming"]}},{"_id":0})。
说明:结果查出来的是8号的数据,没有7号,因为7号虽然爱好音乐,但是不爱好游泳,只有两个都爱好才会查询出来,第二个参数{“_id”:0}表示查询除了_id这一列外的所有列。想指定查询出那些咧可以用 “列名”:1、如:db.scores.find({},{"_id":0,"name":1})
限制查询的结果个数和跳过文档树限制查询结果个数:
1.8、exists查询($exists):依据字段存在与否进行查询:
查询填写了爱好的学生的信息:db.scores.find({"hobby":{$exists:true}},{"_id":0,"score":0})。
查询没有的可以用db.scores.find({"hobby":{$exists:false}},{"_id":0,"score":0})。
1.9、ne查询($ne):不等于查询:
查询数学成绩不等于88的学生信息: db.scores.find({"score.math":{$ne:88}},{"_id":0,"hobby":0})。
1.10、mod查询($mod):字段取余查询:
查询数学成绩对十取余等于3的学生的信息:db.scores.find({"score.math":{$mod:[10,3]}},{"_id":0,"hobby":0})。
1.11、size查询($size):字段个数查询,字段必须是数组类型的。
查询有3个爱好的学生信息:db.scores.find({"hobby":{$size:3}},{"_id":0,"hobby":0})。
1.12、type查询($type):根据字段的BSON类型进行查询。
查询score字段类型为object和score.math字段为double的数据:
1.13、正则表达式匹配
查询姓名以7开头的学生的信息:
db.scores.find({"name":/^7/},{"_id":0})或者db.scores.find({"name":{$regex:/^7/}},{"_id":0})。
MongoDB采用PCRE解析正则表达式。
有效标志位为:
i:匹配大小写
db.scores.find({"name":{$regex:/^T/i}},{"_id":0})。或
db.scores.find({"name":{$regex:/^T/,$options: 'i'}},{"_id":0})。
其它:m,x,s等。
1.14、not查询($not):非查询
查询没有爱好匹配sw的学生的信息:
db.scores.find({"hobby":{$not:/^sw/}},{"_id":0})。
注意:$not不支持用{$regex:…}正则表达式语法。
1.15、排序
按数学成绩升序排列:db.scores.find({},{"_id":0,"hobby":0}).sort({"score.math":1})
降序排列:db.scores.find({},{"_id":0,"hobby":0}).sort({"score.math":-1})
1.16、distinct:去掉重复的
1.17、null
查询没填写爱好的学生的信息:db.scores.find({"hobby":null},{"_id":0})。包括不包含字段和字段值为null的数据。
1.18、where查询。
http://blog.sina.com.cn/s/blog_4a005ecb0100x9od.html
说的有理,效率低下。
|