您的位置:首页 > 数据库 > Mongodb

MongoDB 数据库操作(三)-高级查询

2013-04-09 13:22 459 查看
高级查询:

1.比较操作符

db.collection.find({ "field" : { $gt: value } } ); // 大于: field > value
db.collection.find({ "field" : { $lt: value } } ); // 小于: field < value
db.collection.find({ "field" : { $gte: value } } ); // 大于等于: field >= value
db.collection.find({ "field" : { $lte: value } } ); // 小于等于: field <= value
//如果要同时满足多个条件,可以这样做
db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value


2.all操作

in 只需满足( )内的某一个值即可, 而$all 必

须满足[ ]内的所有值,例如:

db.users.find({age : {$all : [6, 8]}});
可以查询出 {name: 'David', age: 26, age: [ 6, 8, 9 ] }

但查询不出 {name: 'David', age: 26, age: [ 6, 7, 9 ] }

3.exists判断字段是否存在

//查询所有存在age 字段的记录
db.users.find({age: {$exists: true}});
//查询所有不存在name 字段的记录
db.users.find({name: {$exists: false}});


4.Null值

//这条语句查到的是age字段为null的和不存在age字段的集合
db.c2.find({age:null})
//这条语句查询age字段存在,并且为null的
db.c2.find({age:{"$in":[null], "$exists":true}})


5.mod运算

//对age字段10取余,余数为1的。
db.student.find( { age: { $mod : [ 10 , 1 ] } } )


6.ne 不等于

//x字段不等于3的所有记录
db.things.find( { x : { $ne : 3 } } );


7.in 包含于

//与sql 标准语法的用途是一样的,即要查询的是一系列枚举值的范围内查询x 的值在2,4,6 范围内的数据
db.things.find({x:{$in: [2,4,6]}});


8.nin不包含于

与in操作相反:

//查询的是不在一系列枚举值的范围内,查询x 的值不在2,4,6 范围内的数据
//如果有数据不存在x字段,也会返回,系统认为这个字段为null,也不在范围内。
db.things.find({x:{$nin: [2,4,6]}});


9.size运算

对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录

匹配db.users.find({favorite_number: {$size: 3}});

不匹配db.users.find({favorite_number: {$size: 2}});

10.正则表达式

查询不匹配name=B*带头的记录

db.users.find({name: {$not: /^B.*/}});


11.where查询

db.c1.find( { $where: "this.a > 3" } );


12.JS查询

f = function() { return this.a > 3; } db.c1.find(f);


13.count查询,统计数量

//count 查询记录条数
db.users.find().count();
//以下返回的不是5,而是user 表中所有的记录数量
db.users.find().skip(10).limit(5).count();
//如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
db.users.find().skip(10).limit(5).count(true);


14.skip 指定返回结果的起点(0是起点,而不是1)

//从第3 条记录开始,返回5 条记录(limit 3, 5)
db.users.find().skip(3).limit(5);


15.sort 排序

//以年龄升序asc
db.users.find().sort({age: 1});
//以年龄降序desc
db.users.find().sort({age: -1});


16.游标

像大多数数据库产品一样,MongoDB 也是用游标来循环处理每一条结果数据,具体语法如下:

for( var c = db.t3.find(); c.hasNext(); ) {
... printjson( c.next());
... }
或者:

db.t3.find().forEach( function(u) { printjson(u); } );
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: