MongoDB 查询文档

  • 语法
    MongoDB 查询数据的语法格式如下:
db.COLLECTION_NAME.find()

该语句是查询collection中全部数据,效果和关系型数据库的语句select * from table 一样

很多时候,我们查询数据库是有条件限制的,不会一次性将所有内容都查找出来,所以就要了解MongoDB查询的语法结构,MongoDB中条件操作符有:

操作 符号 格式
(>) 大于 $gt {<key>:{$gt:<value>}}
(<) 小于 $lt {<key>:{$lt:<value>}}
(>=) 大于等于 $gte {<key>:{$gte:<value>}}
(<= ) 小于等于 $lte {<key>:{$lte:<value>}}

下面是COLLECTION (MessageInfo)中的用来测试的数据

{
    "_id" : ObjectId("5c9c7d14c1e8552244770a58"),
    "messageName" : "msg1",
    "messageId" : "msg1id",
    "messageContent":"hello",
    "createdAt" : "2019-06-13 16:00:00"
}
{
    "_id" : ObjectId("5cc6b6ebd2cbc887276526a1"),
    "messageName" : "msg2",
    "messageId" : "msg2id",
    "messageContent":"hello",
    "createdAt" : "2019-06-13 16:00:01"
}
{
    "_id" : ObjectId("5cc80b1ad2cbc887276634c3"),
    "messageName" : "msg3",
    "messageId" : "msg3id",
    "messageContent":"hi",
    "createdAt" : "2019-06-13 16:00:02"
}
{
    "_id" : ObjectId("5ce7c42ed2cbc887277722cf"),
    "messageName" : "msg4",
    "messageId" : "msg4id",
    "messageContent":"hi",
    "createdAt" : "2019-06-13 16:00:03"
}
  • 例子1 查找collection 中 messageContent 等于"hello"的数据:
  db.MessageInfo.find({"messageContent":"hello"}).pretty() 
  • 例子2 查找collection 中 createdAt 小于 "2019-06-13 16:00:02"的数据:
  db.MessageInfo.find({"createdAt ":{$lt:"2019-06-13 16:00:02"}}).pretty()
  • 例子3 查找collection 中 createdAt 小于等于 "2019-06-13 16:00:02"的数据:
  db.MessageInfo.find({"createdAt ":{$lte:"2019-06-13 16:00:02"}}).pretty()
  • 例子4 查找collection 中 createdAt 大于 "2019-06-13 16:00:02"的数据:
  db.MessageInfo.find({"createdAt ":{$gt:"2019-06-13 16:00:02"}}).pretty()
  • 例子5 查找collection 中 createdAt 大于等于 "2019-06-13 16:00:02"的数据:
  db.MessageInfo.find({"createdAt ":{$gte:"2019-06-13 16:00:02"}}).pretty()
  • 例子6 查找collection 中 messageContent 不等于"hello"的数据:
  db.MessageInfo.find({"messageContent":{$gte:"hello"}}).pretty() 
  • 下面是MongoDB 与 RDBMS Where 语句比较,以便有关系型数据库的经验的同学对比掌握
操作 格式 范例 RDBMS中的类似语句
等于 {<key>:<value>} db.col.find({"column":50}).pretty() where column= 50
小于 {<key>:{$lt:<value>}} db.col.find({"column":{$lt:50}}).pretty() where column< 50
小于或等于 {<key>:{$lte:<value>}} db.col.find({"column":{$lte:50}}).pretty() where column<= 50
大于 {<key>:{$gt:<value>}} db.col.find({"column":{$gt:50}}).pretty() where column> 50
大于或等于 {<key>:{$gte:<value>}} db.col.find({"column":{$gte:50}}).pretty() where column>= 50
不等于 {<key>:{$ne:<value>}} db.col.find({"column":{$ne:50}}).pretty() where column!= 50
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。