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
}