美文网首页
106MongoDB 基础教程--数据查询

106MongoDB 基础教程--数据查询

作者: Jachin111 | 来源:发表于2021-08-22 11:49 被阅读0次

查询语句

find() 语句
启动 MongoDB 服务,因为 MongoDB 并不随系统一起启动,可能以下命令运行后会等一小段的时间才会启动完毕。

sudo service mongodb start

进入 MongoDB 命令行操作界面,在命令行中敲 exit 可以退出。

mongo

find() 用法:db.COLLECTION_NAME.find()

> use post
> db.post.insert([
{
   title: 'MongoDB Overview',
   description: 'MongoDB is no sql database',
   by: 'shiyanlou',
   url: 'https://www.lanqiao.cn',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
},
{
   title: 'NoSQL Database',
   description: "NoSQL database doesn't have tables",
   by: 'shiyanlou',
   url: 'https://www.lanqiao.cn',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 20,
   comments: [
      {
         user:'user1',
         message: 'My first comment',
         dateCreated: new Date(2013,11,10,2,35),
         like: 0
      }
   ]
}
])

查询数据,不加任何参数默认返回所有数据记录:

> db.post.find()

这条语句会返回 post 集合中的所有文档,实际应用中不常见,因为这样会导致大量的数据传输,造成服务器响应迟缓甚至失去响应。
pretty() 语句
pretty() 可以使查询输出的结果更美观。

> db.post.find().pretty()

例如:

> db.users.find()
{ "_id" : ObjectId("5c35657e6ee1e0307e215fc8"), "name" : "shiyanlou", "age" : "21" }

> db.users.find().pretty()
{
    "_id" : ObjectId("5c35657e6ee1e0307e215fc8"),
    "name" : "shiyanlou",
    "age" : "21"
}

如果你想让 mongo shell 始终以 pretty 的方式显示返回数据,可以通过下面的指令实现:

echo "DBQuery.prototype._prettyShell = true" >> ~/.mongorc.js

这样就把默认的显示方式设置为 pretty 了。

> db.users.find()
{
    "_id" : ObjectId("5c35657e6ee1e0307e215fc8"),
    "name" : "bage",
    "age" : "21"
}

MongoDB 中的 AND

MongoDB 不需要类似于其他数据库的 AND 运算符,当 find() 中传入多个键值对时,MongoDB 就会将其作为 AND 查询处理。
用法:db.mycol.find({ key1: value1, key2: value2 }).pretty()

> db.post.find({"by":"shiyanlou","to": "chenshi"}).pretty()

如上语句就可以查找出 by 字段为 'shiyanlou',to 字段为 'chenshi' 的所有记录,意思是找出系统中由 shiyanlou 发送给 chenshi 的所有邮件。
它对应的关系型 SQL 语句为:

SELECT * FROM post WHERE by = 'shiyanlou' AND to = 'chenshi'

MongoDB 中的 OR

OR
MongoDB 中,OR 查询语句以 $or 作为关键词,用法如下:

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

操作示例:

> db.post.find({
    $or:[
        {"by":"shiyanlou"},
        {"title": "MongoDB Overview"}
    ]
}).pretty()

它对应的关系型 SQL 语句为:

SELECT * FROM post WHERE by = 'shiyanlou' OR title = 'MongoDB Overview'

同时使用 AND 和 OR

操作范例:

> db.post.find({
    "likes": {$gt:10},
    $or: [
        {"by": "shiyanlou"},
        {"title": "MongoDB Overview"}
    ]
}).pretty()

{$gt:10} 表示大于 10,另外,$lt 表示小于、$gte 表示大于等于、$lte 表示小于等于、$ne 表示不等于。

如果这样的符号记起来稍微有点麻烦,可以根据它们的全写配合记忆:
gt:大于 greater than
lt:小于 less than
gte:大于或等于 greater than equal
lte:小于或等于 less than equal

课后习题

请新建一个学生表的集合,插入学生的信息,包括姓名、年龄、性别等,使用上述讲的查询方法查询性别为男的学生、年龄大于 20 的学生和姓张的学生。

练习题注意事项:
在插入数据的时候可能需要多行输入,注意括号不要直接输入完整的一对,可以先敲出左边括号,然后回车写数据,等数据全部写完后再补充右括号,因为 mongodb shell 会把右括号判断为指令结束,不等输入数据就执行语句。
MongoDB 的模糊查询可以用正则匹配的方式实现

# 以 'start' 开头的匹配式:
{"name":/^start/}

# 以 'tail' 结尾的匹配式:
{"name":/tail$/}
> use practice
switched to db practice

> db.createCollection("student")
{ "ok" : 1 }

> db.student.insert([
{
   "name":"黄豆",
   "age":21,
   "gender":"female"
},
{
   "name":"周大壮",
   "age":20,
   "gender":"male"
},
{
   "name":"张小妹",
   "age":17,
   "gender":"female"
}])

BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 3,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})

> db.student.find({"gender":"male"})
{
    "_id" : ObjectId("5c3593ef5b79be0e0e096e55"),
    "name" : "周大壮",
    "age" : 20,
    "gender" : "male"
}

> db.student.find({"age":{$gt:20}})
{
    "_id" : ObjectId("5c3593ef5b79be0e096e5587"),
    "name" : "黄豆",
    "age" : 21,
    "gender" : "female"
}

> db.student.find({"name":/^张/})
{
    "_id" : ObjectId("5c3593ef5b79be0e096e5588"),
    "name" : "张小妹",
    "age" : 17,
    "gender" : "female"
}

相关文章

网友评论

      本文标题:106MongoDB 基础教程--数据查询

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