MongoDB_07_复杂查询

复杂查询

  • 正则的复杂条件查询

MongoDB的模糊查询是通过正则表达式的方式实现的。

语法:
db.collection名.find({field:/正则表达式/})
使用的正则表达式语法是JS正则语法,直接量写法

示例:
    查询评论内容包含"绩笑"的所有文档
db.comment.find({content:/绩笑/})
	查询评论的内容以"专家"开头
db.comment.find({content:/^专家/})

  • 比较查询

    <.<=,>,>=这些操作符也很常用,格式如下:
    
    db.collection名.find({"field":{ $gt: value }})   // field 大于 value
    
    $gt, $lt, $gte, $lte, $ne =======>和shell类似
    
    
    例子:
        db.comment.find({likenum:{$gt : NumberInt(500)}})
    
    执行:
    > db.comment.find({likenum:{$gt : NumberInt(500)}})
    { "_id" : 5, "articleid" : "100000", "content" : "我爱你,绩笑", "userid" : "1005", "nickname" : "jixiao", "createdatetime" : ISODate("2020-02-28T08:00:24.463Z"), "likenum" : 520, "state" : null }
    > db.comment.find({likenum:{$gt : NumberInt(800)}})
    >        
    
    
  • 包含查询

    包含查询使用$in操作符
    示例:查询评论的集合中userid包含1003和1004的文档
    db.comment.find({userid:{$in:["1003","1004"]}})
    
    查询评论的集合中userid不包含1003和1004的文档
    db.comment.find({userid:{$nin:["1003","1004"]}})
    
  • 条件连接查询

     我们如果需要查询同时满足两个以上的条件,需要使用$and
      格式:
     $and:[{},{},{}]
            
    例子:
    查询评论集合中likenum大于9且小于2000的文档.
    db.comment.find({$and:[{likenum:{$gt:NumberInt(500)}},{likenum:{$lt:NumberInt(2000)}}]})
    
    
    执行:
    > db.comment.find({$and:[{likenum:{$gt:NumberInt(9)}},{likenum:{$lt:NumberInt(2000)}}]})
    { "_id" : "2", "articleid" : "100002", "content" : "我爱你,绩憨憨2", "userid" : "1002", "nickname" : "hanhan", "createdatetime" : ISODate("2020-02-28T14:45:54.235Z"), "likenum" : 10, "state" : null }
    { "_id" : "3", "articleid" : "100003", "content" : "我爱你,绩憨憨3", "userid" : "1003", "nickname" : "hanhan", "createdatetime" : ISODate("2020-02-28T14:45:54.235Z"), "likenum" : 10, "state" : null }
    { "_id" : "4", "articleid" : "100004", "content" : "我爱你,绩憨憨4", "userid" : "1004", "nickname" : "hanhan", "createdatetime" : ISODate("2020-02-28T14:45:54.235Z"), "likenum" : 10, "state" : null }
    
    
    
    如果两个以上条件之间是或的关系,就用$or
    格式:
        $or:[{},{},{}]
            
    例子:
        查询评论集合中userid为1003,或者点赞数字小于1000的文档。
        db.comment.find({$or:[{userid:"1003"},{likenum:{$lt:NumberInt(1000)}}]})
    
posted @ 2020-02-28 22:52  Noob52037  阅读(154)  评论(0编辑  收藏  举报