MongoDB查询数据

MongoDB查询
基础语法:
db.collection.find(query, projection)
条件查询的语法:
大于     $gt -------- greater than  >

大于等于  $gte --------- gt equal  >=

小于      $lt -------- less than  <

小于等于   $lte --------- lt equal  <=

不等于     $ne ----------- not equal  !=

等于      $eq  --------  equal  = (不用也可以表示等于)
操作格式范例类似语句
等于{:}db.col.find({“by”:“test”})where by=“test”
小于{:{$lt:}}db.col.find({“id”:{$lt:50}})where id < 50
小于等于{:{$lte:}}db.col.find({“id”:{$lte:50}})where id <= 50
大于{:{$gt:}}db.col.find({“id”:{$gt:50}})where id > 50
大于等于{:{$gte:}}db.col.find({“id”:{$gte:50}})where id >= 50
不等于{:{$ne:}}db.col.find({“id”:{$ne:50}})where id != 50

示例:

-- 查询monitor_log集合(monitor_log表)中的id字段中大于50小于100的数据;
db.getCollection("monitor_log").find({"id":{$gt:50,$lt:100}})
AND查询的语法:

{key1:value1,key2:value2}

多个条件做交集查询时,通过逗号区分多个条件;

>db.col.find({key1:value1, key2:value2}).pretty()

示例:

-- 查询monitor_log表中id,apiId,customerId字段匹配的对应的数据
db.getCollection('monitor_log').find( {"customId" : NumberLong('680366204745804912'),"apiId":1, "_id" : NumberLong('1422414354199871488')})
OR 查询的语法:

多个条件做并集查询时,通过$or来标识,具体语法如下

$or: [{key1: value1}, {key2:value2}]

db.col.find(
   {
      $or: [{key1: value1}, {key2:value2}]
   }
)

示例:

-- 查询apiId的值为1或6的数据
db.getCollection('monitor_log').find({$or:[{"apiId":1},{"apiId":6}]})
and与or联合使用的示例:
db.col.find({"likes": {$gt:50}, $or: [{"by": "菜鸟教程"},{"title": "MongoDB 教程"}]})

当集合中的数据为如下信息时:

{
    "_id" : ObjectId("5f44fc3a4da06abb7cbacfb6"),
    "apiId" : 1,
    "customId" : NumberLong(503441621478509103),
    "time" : "2020-08-25 19:55",
    "success" : NumberLong(1),
    "timestamp" : NumberLong(1598356538150),
    "total" : NumberLong(1)
}

若需要查询某个customerId的数据,若customerId字段值的长度超过一定长度需要用NumberLong('503441621478509103')的形式转换

-- 通过下面的语句无法查询出数据
db.getCollection('monitor_log').find({"apiId" : 1,"customerId" : NumberLong(503441621478509103)});
db.getCollection('monitor_log').find({"apiId" : 1,"customerId" : 503441621478509103});

-- 当数据值没有超过一定的长度,通过该语句能查询出对应的数据
db.getCollection('monitor_log').find({"invokeTime" : 1598495264457});

-- 当数据超过一定的长度后,需要通过字符串转换为NumberLong的形式,来查询数据
db.getCollection('monitor_log').find({"apiId" : 6,"customerId" : NumberLong('503441621478509103')});

查询出的结果如下:

{
    "_id" : NumberLong(1410088365277052928),
    "apiId" : 6,
    "invokeTime" : NumberLong(1598495264457),
    "returnTime" : NumberLong(1598495273216),
    "customerId" : NumberLong(503441621478509103),
    "usedTime" : 8759,
    "success" : 1,
    "failure" : 0,
    "badRequest" : 0,
    "serverError" : 0,
    "statusCode" : 200
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值