2.mongodb查询语言系统
1. 查询选择器
|
| 选择器 | 查询语句 |
|
| 精确匹配选择器 | db.customers.find({id:9}) db.customers.find({cust_id:123,name:"liuyong"}) – and条件 |
| $lt | 小于选择器 | db.customers.find({cust_id:{$lt:200}}) |
| $lte | 小于等于 | db.customers.find({cust_id:{$lte:123}}) |
| $gt | 大于 | db.customers.find({cust_id:{$gt:122}}) |
| $gte | 大于等于 | db.customers.find({cust_id:{$gte:123}}) |
| $in | 范围选择器:是 | db.customers.find({cust_id:{$in:[123,124]}}) |
| $nin | 范围选择器:否 | db.customers.find({cust_id:{$nin:[123,124]}}) |
| $ne | 不等于 | db.customers.find({cust_id:{$ne:1}}) |
| $or | 或运算选择器 | db.customers.find({$or:[{cust_id:123},{name:"liuyong"}]}) |
| $and | 与运算选择器 | > db.customers.find({$and:[{cust_id:123},{name:"liuyong"}]}) |
| $exists | 判断某个字段是否存在,与db.customer.find({cust_id:null})效果一样 | db.customers.find({id:{$exists:false}}) |
|
| 嵌套选择器 | db.customers.find({'products.prod_name':"liuyong"}) db.customers.find({'orders.0.order_id':1}) |
2. 查询投射
1. 投射项使用
查询语句:db.customers.find({cust_id:{$gte:100},name:"liuyong"},{_id:0,cust_id:1,name:1}
返回结果:"cust_id" : 123, "name" : "liuyong" }
解析:
第一步:查询cust_id大于等于100并且name等于liuyong的文档集合。
第二部:指定需要显示那些文档列,_id:0指示不现实_id列,cust_id和name列显示。
2. 排序
db.customers.find({}).sort({id:-1})
按照id降序。
注意:排序比较浪费时间,所以在排序的字段上要确保建立了索引,而且排序执行计划能够高效的利用索引。
3. 分页
db.customers.find({}).skip(1).limit(5).sort({cust_id:-1})
跳过1条数据,返回5条数据,按cust_id倒序。
注意:当skip数据较大时,会导致扫描较大的范围,所以尽量不要使用skip。
3.数组操作
构造测试条件:
> db.ArrayTest.insert({id:1,AttributeName:"material",AttributeValue:["牛仔","植
棉","雪纺","蕾丝"],IsOptional:1})
WriteResult({ "nInserted" : 1 })
> db.ArrayTest.find({})
{ "_id" : ObjectId("5740752521a372ee15070976"), "id" : 1, "AttributeName" : "mat
erial", "AttributeValue" : [ "牛仔", "植棉", "雪纺", "蕾丝" ], "IsOptional" : 1
}
> db.ArrayTest.insert({id:2,AttributeName:"version",AttributeValue:["收腰型","修
身型","直筒型","宽松型","其它"]})
WriteResult({ "nInserted" : 1 })
> db.ArrayTest.find({})
{ "_id" : ObjectId("5740752521a372ee15070976"), "id" : 1, "AttributeName" : "mat
erial", "AttributeValue" : [ "牛仔", "植棉", "雪纺", "蕾丝" ], "IsOptional" : 1
}
{ "_id" : ObjectId("574075af21a372ee15070977"), "id" : 2, "AttributeName" : "ver
sion", "AttributeValue" : [ "收腰型", "修身型", "直筒型", "宽松型", "其它" ] }
3.1精确匹配
db.ArrayTest.find({AttributeValue:[ "牛仔", "植棉", "雪纺", "蕾丝" ]})
3.2匹配数组中的一个元素值
db.ArrayTest.find({AttributeValue:"收腰型"})})
3.3匹配指定位置的元素值
db.ArrayTest.find({'AttributeValue.0':"收腰型"})})
3.4指定数组索引并匹配嵌套文档中的字段值
构造测试数据:
> db.Order.insert({id:1,StatusInfo:[{status:9,desc:"已取消"},{status:2,desc:"已"
付款"}]})
查询语句:db.Order.find({'StatusInfo.0.status':9})
返回结果:
{ "_id" : ObjectId("5740863d21a372ee15070978"), "id" : 1, "StatusInfo" : [ { "st
atus" : 9, "desc" : "已取消" }, { "status" : 2, "desc" : "已付款" } ] }
查询语句:db.Order.find({id:1},{_id:0,StatusInfo:1})
返回结果:
{ "StatusInfo" : [ { "status" : 9, "desc" : "已取消" }, { "status" : 2, "desc" :
"已付款" } ] }

浙公网安备 33010602011771号