mongodb相关查询总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangkezhi_471885889/article/details/54137944
1.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,小于value2

1.2$all匹配所有(满足[]内的所有值)
    db.users.find({age : {$all : [6, 8]}});    
    可以查出{name : "zhangsan", age:[6, 8, 9]},查不出{name : "zhangsan", age : [6, 7, 9]}

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

1.4Null值处理
     Null值的处理稍微有一点奇怪 ,”null”不仅能找到它自身,连不存在该字段的记录页可以被找出来。所以我们要使用exits来限制。
    db.users.find({age : {"$in" : [null], "$exists" : true}});

1.5 $mod 取模运算
    查询 age 取模 10 等于 0 的数据
    db.student.find({age: {$mod : [ 10 , 0 ]}} )

1.6$ne 不等于
    db.users.find({age : {$ne : 20}});

1.7$in 包含(与sql用法一样)
    db.users.find({age : {$in : [20, 25, 30]}});
    db.users.find({name : /张/});//模糊查询名字出现'张'
    db.getCollection('data').find({"type" : {$in : [/资金不足/]}});//模糊查询type数组中包含'资金不足'

1.8$nin 不包含
    db.users.find({age : {$nin : [18, 20, 21]}});

1.9$size 数组元素个数
    db.users.find({subjects : {$size : 3}});//查询有三个科目的记录

1.10 正则表达式匹配
    db.users.find({name: {$not: /^B.*/}});//查询不匹配 name=B*带头的记录
    db.getCollection('data').find({"name": {$regex:/liuzhilun.*/i}})//查询name包含liuzhilun

1.11 Javascript 查询和$where 查询
    查询 a 大于 3 的数据,下面的查询方法殊途同归
    db.c1.find({a : {$gt: 3}});
    db.c1.find({$where: "this.a > 3"});
    db.c1.find("this.a > 3");
    f = function() { return this.a > 3; } db.c1.find(f);

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

1.13 skip 限制返回记录的起点
    db.users.find().skip(3).limit(5);//从第 3 条记录开始,返回 5 条记录(limit 3, 5)

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

1.15 查询返回指定的字段
    db.users.find().sort({},{"字段1":1,"字段2":1});//1表示返回、0表示不返回

1.16 去重查询
    db.getCollection('info').distinct("workAddress", {"mobliePhone" : "13266668888"})


**2 添加索引**:
    db.blacklist.ensureIndex({"orderId":"hashed"});//给blacklist表添加orderId的hashed索引

猜你喜欢

转载自blog.csdn.net/zhangkezhi_471885889/article/details/54137944