美文网首页
MongoDB 查找语句 find() 应用汇总

MongoDB 查找语句 find() 应用汇总

作者: 沧海2122537190 | 来源:发表于2019-07-16 14:03 被阅读0次
    db.collection.find(query, projection)

    projection

    返回字段,为可选条件。样式为{字段1:1/0,字段2:1/0....}(0表示该字段在结果集中不显示,1表示该字段显示)
    在结果集中_id字段默认显示,若不需要可用“_id:0”的方式,取消显示

    query

    查询条件,为可选条件。样式为{字段:条件}。
    其中可使用多种查询方式

    1.单一条件查询:

    样式为db.数据库名.find({ 字段1: value1})

    示例:
    db.getCollection("total_journal_issue").find({
    "journal_id" : "307ada8a-727d-4a39-9e34-bd2b611b0c6d"
    })
    
    示例

    2.多条件查询$and

    表示查找条件之间是and关系
    db.数据库名.find({ 字段1: value1, 字段2: value2 })
    或者
    db.数据库名.find({$and[ 字段1: value1, 字段2: value2 ]})
    两种表示意思相同,结果相同

    示例:
    Select * 
    From total_journal_issue 
    Where  journal_id="307ada8a-727d-4a39-9e34-bd2b611b0c6d" 
    and "article_count" = 20;//等同的SQL语句
    
    db.getCollection("total_journal_issue").find({ 
    $and : [
    {"journal_id" : "307ada8a-727d-4a39-9e34-bd2b611b0c6d"},
    {"article_count" : 20 }
    ]})
    
    有and
    db.getCollection("total_journal_issue").find({
    "journal_id" : "307ada8a-727d-4a39-9e34-bd2b611b0c6d", 
    "article_count"  : 20 
    })
    
    无and

    3.多条件查询$or

    表示查找条件之间是or的关系
    db.数据库名.find({$or:[{字段1: value1}, {字段12: value2}]})

    示例:
    Select * 
    From total_journal_issue 
    Where  journal_id="307ada8a-727d-4a39-9e34-bd2b611b0c6d" 
    or "article_count" = 20;//等同的SQL语句
    
    db.getCollection("total_journal_issue").find({ 
    $or : [
    {"journal_id" : "307ada8a-727d-4a39-9e34-bd2b611b0c6d"}, 
    {"article_count" : 20 }
    ]})
    
    or

    4.非等于条件查询

    $ne:不等于 != eg:{"count":{$ne:20}}//count不等于20
    $gt:大于 > eg:{"count":{$gt:20}}//count大于20
    $lt:小于 < eg:{"count":{$lt:20}}//count小于20
    $gte:大于或等于 >= eg:{"count":{$gte:20}}//count大于或等于20
    $lte:小于或等于 <= eg:{"count":{$lte:20}}//count小于或等于20
    $in:值在列表中 eg:{"count":{$in:[10,20,50]}}//count的值等于10,20或者50
    $exists:字段是否存在 
      eg:{"count" : { $exists : false }}//count字段不存在
      eg:{"count" : { $exists : true }}//count字段存在
    $type:查询字段类型(类型见下表) 
      eg:{"count":{$type:"int"}}//count字段是32 位整型数
      eg:{"count":{$type:"16"}}//count字段是32 位整型数
    
    
    类型名称 序号 类型代码 解释
    Double 1 “double” 双精度型
    String 2 “string” 字符串
    Object 3 “object” 对象
    Array 4 “array” 数组
    Binary data 5 “binData” 二进制数据
    ObjectId 7 “objectId” 对象 ID
    Boolean 8 “bool” 布尔类型
    Date 9 “date” 数据
    Null 10 “null”
    Regular Expression 11 “regex” 正则表达式
    JavaScript 13 “javascript” JS 代码
    JavaScript (with scope) 15 “javascriptWithScope” 有作用域的 JS 代码
    32-bit integer 16 “int” 32 位整型数
    Timestamp 17 “timestamp” 时间戳
    64-bit integer 18 “long” 64 位整型数
    Min key -1 “minKey” 最小值
    Max key 127 “maxKey” 最大值

    5.正则查询

    MongoDB 正则查询 $regex
    正则常用查询

    6.其他

    (1)db.c.find({a:null})
    null 不仅匹配自身,还会匹配a字段不存在的值,并返回缺少这个字段的文档

    相关文章

      网友评论

          本文标题:MongoDB 查找语句 find() 应用汇总

          本文链接:https://www.haomeiwen.com/subject/hpnccctx.html