mongodb之安装入门使用

⼀、MongoDb的体系结构

1、NoSql的概念

NoSQL(NoSQL = Not Only SQL ),意即“不仅仅是 SQL ”,互联⽹的早期我们的数据⼤多以关系型数据库来存储的。其特点是规范的数据结构(预定义模式)、强⼀⾄性、表与表之间通过外键进⾏关联,这些特征使我们对数据的管理更加清晰和严谨,但随着互联⽹的发展数据成爆炸式的增⻓我们对数据库需要更好的灵活性和更快的速度。这就是NoSql可以做到的。它不需要预先定义模式,没有主外键关联、⽀持分⽚、⽀持复本。
NoSql的分类
键值(Key-Value)存储数据库
这⼀类数据库主要会使⽤到⼀个哈希表,这个表中有⼀个特定的键和⼀个指针指向特定的数据。Key/value模型对于IT系统来说的优势在于简单、易部署。但是如果DBA只对部分值进⾏查询或更新的时候,Key/value就显得效率低下了。举例如:Tokyo Cabinet/Tyrant,Redis, Voldemort, Oracle BDB.
列存储数据库
这部分数据库通常是⽤来应对分布式存储的海量数据。键仍然存在,但是它们的特点是指向了多个列。这些列是由列家族来安排的。如:Cassandra, HBase, Riak.
⽂档型数据库
⽂档型数据库的灵感是来⾃于Lotus Notes办公软件的,⽽且它同第⼀种键值存储相类似。该类型的数据模型是版本化的⽂档,半结构化的⽂档以特定的格式存储,⽐如JSON。⽂档型数据库可 以看作是键值数据库的升级版,允许之间嵌套键值。⽽且⽂档型数据库⽐键值数据库的查询效率更⾼。如:CouchDB, MongoDb. 国内也有⽂档型数据库SequoiaDB,已经开源。
图形(Graph)数据库
图形结构的数据库同其他⾏列以及刚性结构的SQL数据库不同,它是使⽤灵活的图形模型,并且能够扩展到多个服务器上。NoSQL数据库没有标准的查询语⾔(SQL),因此进⾏数据库查询需要制定数据模型。许多NoSQL数据库都有REST式的数据接⼝或者查询API。如:Neo4J, InfoGrid, Infinite Graph.
 

2、NoSql的应⽤场景

NoSQL数据库在以下的这⼏种情况下⽐较适⽤
1、数据模型⽐较简单;
2、需要灵活性更强的IT系统;
3、对数据库性能要求较⾼;
4、不需要⾼度的数据⼀致性;

 

3、MongoDb的逻辑组成

体系结构:

逻辑结构与关系数据库的对⽐:

关系型数据库mongodb
database(数据库)database(数据库)
table(表)collection(集合)
row(行)document(BSON文档)
index(唯一索引,主键索引)index(全局索引)
join(主外键关联)embedded Document(嵌套文档)
primary key(指定1至N个列做主键)primary key(指定_id field做主键)
aggreation(group by 聚合)aggreation(pipeline、mapReduce)

 

⼆、MongoDb安装配置与基础命令

1. centos系统mongoDb社区版安装配置

1.1下载安装:

下载地址:https://www.mongodb.com/download-center/community

cd /usr/local/src
#下载
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.5.tgz
# 解压
tar -zxvf mongodb-linux-x86_64-4.0.5.tgz

1.2mongodb安装启动参数说明

mongoDb 由C++编写,下载下来的包可以直接启动

#创建数据库目录
mkdir -p /data/mongodb
# 切换到mongodb目录,指定路径启动mongo
cd mongodb-linux-x86_64-4.0.5
./bin/mongod --dbpath=/data/mongodb/

使用配置文件方式启动:

#创建配置文件目录
mkdir conf
#编辑配置文件
vim mongo.conf

#配置文件内容
#dbpath 数据库目录,默认/data/db
dbpath=/data/mongodb/
#port 监听的端口
port=27017
#bind_ip 监听ip地址,默认全部可以访问
bind_ip=0.0.0.0
#fork 是否以后台启动的方式登录
fork=true
#logpath 日志地址
logpath=/data/mongodb/mongodb.log
#logappend 是否追加日志
logappend=true
#auth 是否开启用户密码登录
auth=false
#config 指定配置文件

#保存退出
:wq

#以配置文件方式启动
./bin/mongod -f ./conf/mongo.conf

2.win10安装mongodb

2.1下载地址

https://www.mongodb.com/download-center/community

2.2双击安装,修改安装地址

在安装目录下创建数据目录data,创建配置文件目录conf

在数据data目录下创建db和log目录

启动mongodb服务器:

mongod --dbpath D:\devtools\mongodb\data\db

使用配置文件,将mongodb安装成win服务

在配置文件conf目录下创建配置文件mongodb.cfg

 

配置文件mongodb.cfg内容:

systemLog:
    destination: file
    path: D:\devtools\mongodb\data\log\mongodb.log
storage:
    dbPath: D:\devtools\mongodb\data\db

安装mongodb服务:

#以管理员身份启动命令行窗口
切换到mongodb安装目录:
C:\Windows\system32>d:
cd \devtools\mongodb\bin

安装服务:
D:\devtools\mongodb\bin>mongod --config "D:\devtools\mongodb\conf\mongodb.cfg" --install --serviceName "mongodb"

启动服务:
D:\devtools\mongodb\bin>net start mongodb
mongodb 服务正在启动 ..
mongodb 服务已经启动成功。

关闭服务:
net stop mongodb

移除服务:
D:\devtools\mongodb\bin>mongod.exe --remove

将mongodb安装成windows服务成功:

 

 连接mongodb服务器:

 

D:\devtools\mongodb\bin>mongo
MongoDB shell version v4.2.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("bb390791-ddb1-4751-9d9e-b52a732d4520") }
MongoDB server version: 4.2.1
Server has startup warnings:
2019-11-20T11:20:32.936+0800 I  CONTROL  [initandlisten]
2019-11-20T11:20:32.936+0800 I  CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-11-20T11:20:32.936+0800 I  CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2019-11-20T11:20:32.936+0800 I  CONTROL  [initandlisten]
2019-11-20T11:20:32.936+0800 I  CONTROL  [initandlisten] ** WARNING: This server is bound to localhost.
2019-11-20T11:20:32.936+0800 I  CONTROL  [initandlisten] **          Remote systems will be unable to connect to this server.
2019-11-20T11:20:32.936+0800 I  CONTROL  [initandlisten] **          Start the server with --bind_ip <address> to specify which IP
2019-11-20T11:20:32.936+0800 I  CONTROL  [initandlisten] **          addresses it should serve responses from, or with --bind_ip_all to
2019-11-20T11:20:32.936+0800 I  CONTROL  [initandlisten] **          bind to all interfaces. If this behavior is desired, start the
2019-11-20T11:20:32.936+0800 I  CONTROL  [initandlisten] **          server with --bind_ip 127.0.0.1 to disable this warning.
2019-11-20T11:20:32.936+0800 I  CONTROL  [initandlisten]
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

>

 使用MongoDB Compass 图形界面管理工具连接mongodb:

下载地址:https://www.mongodb.com/download-center/compass

双击安装包,安装启动后连接:

 

3.客户端Shell 的使⽤及参数说明
 

#启动mongo shell客户端 连接 本机的默认端口
[root@iZ8vb32fixtn14esukg0vsZ mongodb-linux-x86_64-4.0.5]# ./bin/mongo
MongoDB shell version v4.0.5
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("6b6252b6-3962-41ff-a822-9d8aa3b64fde") }
MongoDB server version: 4.0.5
Server has startup warnings: 
2019-11-12T14:14:32.160+0800 I STORAGE  [initandlisten] 
2019-11-12T14:14:32.160+0800 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2019-11-12T14:14:32.160+0800 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2019-11-12T14:14:33.696+0800 I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2019-11-12T14:14:33.696+0800 I CONTROL  [initandlisten] 
2019-11-12T14:14:33.697+0800 I CONTROL  [initandlisten] 
2019-11-12T14:14:33.697+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2019-11-12T14:14:33.697+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2019-11-12T14:14:33.697+0800 I CONTROL  [initandlisten] 
2019-11-12T14:14:33.697+0800 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2019-11-12T14:14:33.697+0800 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2019-11-12T14:14:33.697+0800 I CONTROL  [initandlisten] 
2019-11-12T14:14:33.697+0800 I CONTROL  [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 3900 processes, 65535 files. Number of processes should be at least 32767.5 : 0.5 times number of files.
2019-11-12T14:14:33.697+0800 I CONTROL  [initandlisten] 

# 指定IP和端口
./bin/mongo --host=127.0.0.1 --port=27017

 mongo shell 是⼀个js 控制台,可以执⾏js 相关运算如:

> 1+1
2
> var a=1;
> a
1
> 

4.数据库与集合的基础操作

MongoDB 中默认的数据库为 test,如果你没有创建新的数据库,集合将存放在 test 数据库中。
#查看数据库
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> show databases
admin   0.000GB
config  0.000GB
local   0.000GB

#切换数据库(如果数据库不存在则创建数据库)
> use zyf
switched to db zyf

#查看当前使用的数据库名
> db
zyf

#查看数据库中的集合 此时为空
>show tables

>show collections


#插入数据,在插入数据时如果没有数据库和集合,则会自动创建数据库与集合
db.friend.insertOne({name:"wukong",sex:"man"});

#此时再次查看数据库和集合,zyf数据库和user集合都已存在
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
zyf     0.000GB
> show databases
admin   0.000GB
config  0.000GB
local   0.000GB
zyf     0.000GB

> show tables
user
> show collections
user

#删除集合
> db.user.drop()
true

> show tables

#删除当前数据库,默认是test,可以使用 db 命令查看当前数据库名
> db.dropDatabase();

三、MongoDB CRUD

创建集合

db.createCollection(name, options)
参数说明:
    name: 要创建的集合名称
    options: 可选参数, 指定有关内存大小及索引的选项

在 test 数据库中创建 user 集合:
> use test
switched to db test

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

创建固定集合user1,整个集合空间大小 6142800 KB, 文档最大个数为 10000 个
> db.createCollection("user1", { capped : true, autoIndexId : true, size : 6142800, max : 10000 } )
{ "ok" : 1 }

options 可以是如下参数: 

删除集合

db.collectionName.drop();
如果成功删除选定集合,则 drop() 方法返回 true,否则返回 false。

>use test
switched to db test
>show collections
user
user1

删除集合 user :
>db.user.drop()
true

插入文档

//员工表
db.emp.insert([
	{_id:1101,name:'111' ,job:'讲师'  ,dep:'讲师部',salary:10000},
	{_id:1102,name:'222' ,job:'讲师'  ,dep:'讲师部',salary:10000},
	{_id:1103,name:'333' ,job:'讲师'  ,dep:'讲师部',salary:10000},
	{_id:1105,name:'444' ,job:'讲师'  ,dep:'讲师部',salary:8000},
	{_id:1106,name:'555' ,job:'校长'  ,dep:'校办'  ,salary:20000},
	{_id:1107,name:'666' ,job:'班主任',dep:'客服部',salary:8000},
	{_id:1108,name:'777' ,job:'班主任',dep:'客服部',salary:8000},
	{_id:1109,name:'888' ,job:'教务'  ,dep:'教务处',salary:8000},
	{_id:1110,name:'999' ,job:'教务' ,dep:'教务处' ,salary:8000},
	{_id:1111,name:'000' ,job:'助教' ,dep:'客服部' ,salary:5000},
	{_id:1112,name:'001' ,job:'助教' ,dep:'客服部' ,salary:3000}
	]);
	
//学生表
db.stu.insertMany([
	{name:"111",age:1,grade:{redis:50,java:60,js:70,zk:80}}, 
	{name:"222",age:2,grade:{redis:52,java:62,js:90,zk:81}} ,
	{name:"333",age:3,grade:{redis:76,java:63,js:89,zk:34}} ,
	{name:"444",age:4,grade:{redis:224,java:43,js:77,zk:99}}
	]);

//课目表	
db.subject.insertMany([
	{stu:"111",subjects:["redis","java","js","zk"]}, 
	{stu:"222",subjects:["redis","java","js","zk"]},
	{stu:"333",subjects:["redis","java","js","zk"]},
	{stu:"444",subjects:["redis","java","js","zk"]}
	])

//科目2表
db.subject2.insertMany([
	{_id:"001",stu:"111",subjects:[{name:"redis",hour:12},{name:"dubbo",hour:120},{name:"zookeper",hour:56}]},
	{_id:"002",stu:"222",subjects:[{name:"java",hour:120},{name:"mysql",hour:10},{name:"oracle",hour:30}]},
	{_id:"003",stu:"333",subjects:[{name:"mysql",hour:12},{name:"html5",hour:120},{name:"netty",hour:56}]},
	{_id:"004",stu:"444",subjects:[{name:"redis",hour:12},{name:"dubbo",hour:120},{name:"netty",hour:56}]}
	])

//课程表
db.course.insert([
    { _id: 1, name: "Java Script", description: "name is js and jquery" },
     { _id: 2, name: "Git", description: "Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency" },
     { _id: 3, name: "Apache dubbo", description: "Apache Dubbo  is a high-performance, java based open source RPC framework.阿里 开源 项目" },
     { _id: 4, name: "Redis", description: "Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures" },
     { _id: 5, name: "Apache ZooKeeper", description: "Apache ZooKeeper is an effort to develop and maintain an open-source server which enables highly reliable distributed coordination" }
   ])	

更新文档

update() 方法用于更新已存在的文档
db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

参数说明:

query : update的查询条件,类似sql update查询内where后面的。
update : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的
upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。
multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。
writeConcern :可选,抛出异常的级别。

#设置值
> db.emp.update({_id:1101},{$set:{salary:10001}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.emp.find({_id:1101})
{ "_id" : 1101, "name" : "111", "job" : "讲师", "dep" : "讲师部", "salary" : 10001 }

#自增
> db.emp.update({_id:1101} ,{ $inc:{salary:200}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.emp.find({_id:1101})
{ "_id" : 1101, "name" : "111", "job" : "讲师", "dep" : "讲师部", "salary" : 10201 }


#只更新一条
> db.emp.find({dep:"客服部"})
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8000 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8000 }
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5000 }
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3000 }
> db.emp.update({dep:"客服部"},{$inc:{salary:100}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.emp.find({dep:"客服部"})
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8100 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8000 }
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5000 }
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3000 }

#设置参数multi为true更新多条
> db.emp.find({dep:"客服部"})
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8100 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8000 }
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5000 }
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3000 }
> db.emp.update({dep:"客服部"},{$inc:{salary:100}},false,true)
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })
> db.emp.find({dep:"客服部"})
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8200 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8100 }
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5100 }
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3100 }


#使用updateMany()方法更新多条
> db.emp.find({dep:"客服部"})
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8200 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8100 }
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5100 }
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3100 }
> db.emp.updateMany({dep:"客服部"},{$inc:{salary:100}})
{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 4 }
> db.emp.find({dep:"客服部"})
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8300 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8200 }
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5200 }
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3200 }


#使用save()方法根据id更新整个document
> db.emp.find({_id:1101})
{ "_id" : 1101, "name" : "111", "job" : "讲师", "dep" : "讲师部", "salary" : 10201 }
> db.emp.save({ "_id" : 1101, "name" : "11101", "job" : "讲师1", "dep" : "讲师部1", "salary" : 102011 })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.emp.find({_id:1101})
{ "_id" : 1101, "name" : "11101", "job" : "讲师1", "dep" : "讲师部1", "salary" : 102011 }

 

查询文档

基础查询:

#使用find() 方法以非结构化的方式来显示所有文档

语法:
db.collection.find(query, projection)
    query :可选,使用查询操作符指定查询条件
    projection :可选,使用投影操作符指定返回的键。查询时返回文档中所有键值, 只需省略该参数即可(默认省略)。

pretty() 方法以格式化的方式来显示所有文档

> db.emp.find().pretty();
{
	"_id" : 1101,
	"name" : "11101",
	"job" : "讲师1",
	"dep" : "讲师部1",
	"salary" : 102011
}
{
	"_id" : 1102,
	"name" : "222",
	"job" : "讲师",
	"dep" : "讲师部",
	"salary" : 10000
}
{
	"_id" : 1103,
	"name" : "333",
	"job" : "讲师",
	"dep" : "讲师部",
	"salary" : 10000
}


#查看集合中全部数据
> db.emp.find()
{ "_id" : 1101, "name" : "11101", "job" : "讲师1", "dep" : "讲师部1", "salary" : 102011 }
{ "_id" : 1102, "name" : "222", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1103, "name" : "333", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1105, "name" : "444", "job" : "讲师", "dep" : "讲师部", "salary" : 8000 }
{ "_id" : 1106, "name" : "555", "job" : "校长", "dep" : "校办", "salary" : 20000 }
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8300 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8200 }
{ "_id" : 1109, "name" : "888", "job" : "教务", "dep" : "教务处", "salary" : 8000 }
{ "_id" : 1110, "name" : "999", "job" : "教务", "dep" : "教务处", "salary" : 8000 }
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5200 }
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3200 }

#基于ID查找
> db.emp.find({_id:1101})
{ "_id" : 1101, "name" : "11101", "job" : "讲师1", "dep" : "讲师部1", "salary" : 102011 }

#基于属性查找,可以传入多个键(key),每个键(key)以逗号隔开,即常规 SQL 的 AND 条件
> db.emp.find({name:"11101"},job:"讲师1")
{ "_id" : 1101, "name" : "11101", "job" : "讲师1", "dep" : "讲师部1", "salary" : 102011 }

#条件操作符:大于 - $gt ,小于 - $lt ,大于等于 - $gte ,小于等于 - $lte
> db.emp.find({name:"11101",salary:{$gt:8000}})
{ "_id" : 1101, "name" : "11101", "job" : "讲师1", "dep" : "讲师部1", "salary" : 102011 }
> db.emp.find({job:"讲师",salary:{$gt:8000}})
{ "_id" : 1102, "name" : "222", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1103, "name" : "333", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }

#运算符 in
> db.emp.find({job:{$in:["讲师","班主任"]}})
{ "_id" : 1102, "name" : "222", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1103, "name" : "333", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1105, "name" : "444", "job" : "讲师", "dep" : "讲师部", "salary" : 8000 }
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8300 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8200 }

#运算符 or
> db.emp.find({$or:[{job:"讲师",salary:{$gt:8000}}]})
{ "_id" : 1102, "name" : "222", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1103, "name" : "333", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }

#运算符 or 和 大于
> db.emp.find({$or:[{job:"讲师"},{salary:{$gt:8000}}]})
{ "_id" : 1101, "name" : "11101", "job" : "讲师1", "dep" : "讲师部1", "salary" : 102011 }
{ "_id" : 1102, "name" : "222", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1103, "name" : "333", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1105, "name" : "444", "job" : "讲师", "dep" : "讲师部", "salary" : 8000 }
{ "_id" : 1106, "name" : "555", "job" : "校长", "dep" : "校办", "salary" : 20000 }
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8300 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8200 }

#运算符 or
> db.emp.find({$or:[{job:"讲师"},{job:"客服部"}]})
{ "_id" : 1102, "name" : "222", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1103, "name" : "333", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1105, "name" : "444", "job" : "讲师", "dep" : "讲师部", "salary" : 8000 }

排序与分页: 

#使用sort()方法对数据进行排序,sort() 方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序排列,而 -1 是用于降序排列
> db.emp.find().sort({dep:1,salary:-1})
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8300 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8200 }
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5200 }
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3200 }
{ "_id" : 1109, "name" : "888", "job" : "教务", "dep" : "教务处", "salary" : 8000 }
{ "_id" : 1110, "name" : "999", "job" : "教务", "dep" : "教务处", "salary" : 8000 }
{ "_id" : 1106, "name" : "555", "job" : "校长", "dep" : "校办", "salary" : 20000 }
{ "_id" : 1102, "name" : "222", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1103, "name" : "333", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1105, "name" : "444", "job" : "讲师", "dep" : "讲师部", "salary" : 8000 }
{ "_id" : 1101, "name" : "11101", "job" : "讲师1", "dep" : "讲师部1", "salary" : 102011 }
> db.emp.find().sort({dep:1,salary:1})
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3200 }
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5200 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8200 }
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8300 }
{ "_id" : 1109, "name" : "888", "job" : "教务", "dep" : "教务处", "salary" : 8000 }
{ "_id" : 1110, "name" : "999", "job" : "教务", "dep" : "教务处", "salary" : 8000 }
{ "_id" : 1106, "name" : "555", "job" : "校长", "dep" : "校办", "salary" : 20000 }
{ "_id" : 1105, "name" : "444", "job" : "讲师", "dep" : "讲师部", "salary" : 8000 }
{ "_id" : 1102, "name" : "222", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1103, "name" : "333", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1101, "name" : "11101", "job" : "讲师1", "dep" : "讲师部1", "salary" : 102011 }

#使用skip()方法跳过指定数量的数据,skip方法接受一个数字参数作为跳过的记录条数
> db.emp.find().sort({dep:1,salary:1}).skip(0);
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3200 }
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5200 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8200 }
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8300 }
{ "_id" : 1109, "name" : "888", "job" : "教务", "dep" : "教务处", "salary" : 8000 }
{ "_id" : 1110, "name" : "999", "job" : "教务", "dep" : "教务处", "salary" : 8000 }
{ "_id" : 1106, "name" : "555", "job" : "校长", "dep" : "校办", "salary" : 20000 }
{ "_id" : 1105, "name" : "444", "job" : "讲师", "dep" : "讲师部", "salary" : 8000 }
{ "_id" : 1102, "name" : "222", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1103, "name" : "333", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1101, "name" : "11101", "job" : "讲师1", "dep" : "讲师部1", "salary" : 102011 }
> db.emp.find().sort({dep:1,salary:1}).skip(1);
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5200 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8200 }
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8300 }
{ "_id" : 1109, "name" : "888", "job" : "教务", "dep" : "教务处", "salary" : 8000 }
{ "_id" : 1110, "name" : "999", "job" : "教务", "dep" : "教务处", "salary" : 8000 }
{ "_id" : 1106, "name" : "555", "job" : "校长", "dep" : "校办", "salary" : 20000 }
{ "_id" : 1105, "name" : "444", "job" : "讲师", "dep" : "讲师部", "salary" : 8000 }
{ "_id" : 1102, "name" : "222", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1103, "name" : "333", "job" : "讲师", "dep" : "讲师部", "salary" : 10000 }
{ "_id" : 1101, "name" : "11101", "job" : "讲师1", "dep" : "讲师部1", "salary" : 102011 }

#使用limit()方法,接受一个数字参数,该参数指定从MongoDB中读取的记录条数
> db.emp.find().sort({dep:1,salary:1}).skip(1).limit(3);
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5200 }
{ "_id" : 1108, "name" : "777", "job" : "班主任", "dep" : "客服部", "salary" : 8200 }
{ "_id" : 1107, "name" : "666", "job" : "班主任", "dep" : "客服部", "salary" : 8300 }

$type操作符:

$type操作符是基于BSON类型来检索集合中匹配的数据类型,并返回结果。

MongoDB 中可以使用的类型:

类型	                    数字	备注
Double	                    1	 
String	                    2	 
Object	                    3	 
Array	                    4	 
Binary data	                5	 
Undefined	                6	    已废弃。
Object id	                7	 
Boolean	                    8	 
Date	                    9	 
Null	                    10	 
Regular Expression	        11	 
JavaScript	                13	 
Symbol	                    14	 
JavaScript (with scope)	    15	 
32-bit integer	            16	 
Timestamp	                17	 
64-bit integer	            18	 
Min key	                    255	    Query with -1.
Max key	                    127	 

$type 实例:
> db.emp.find()
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5200 }
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3200 }
{ "_id" : 1113, "name" : 1, "job" : "助教", "dep" : "客服部", "salary" : 3200 }
获取 emp 集合中 name 为 String 的数据:
db.emp.find({"name" : {$type : 2}})
或
db.emp.find({"name" : {$type : 'string'}})
{ "_id" : 1111, "name" : "000", "job" : "助教", "dep" : "客服部", "salary" : 5200 }
{ "_id" : 1112, "name" : "001", "job" : "助教", "dep" : "客服部", "salary" : 3200 }

 

嵌套查询:

# stu集合包含 复合属性 grade
> db.stu.find();
{ "_id" : ObjectId("5dccc542787a8449d387b655"), "name" : "111", "age" : 1, "grade" : { "redis" : 50, "java" : 60, "js" : 70, "zk" : 80 } }
{ "_id" : ObjectId("5dccc542787a8449d387b656"), "name" : "222", "age" : 2, "grade" : { "redis" : 52, "java" : 62, "js" : 90, "zk" : 81 } }
{ "_id" : ObjectId("5dccc542787a8449d387b657"), "name" : "333", "age" : 3, "grade" : { "redis" : 76, "java" : 63, "js" : 89, "zk" : 34 } }
{ "_id" : ObjectId("5dccc542787a8449d387b658"), "name" : "444", "age" : 4, "grade" : { "redis" : 224, "java" : 43, "js" : 77, "zk" : 99 } }

# 错误示例:无结果
> db.stu.find({grade:{redis:50,java:60}});

# 错误示例:无结果
> db.stu.find({grade:{"redis" : 50, "java" : 60, "js" : 70}});

# 基于复合属性查找 时必须包含其所有的值 并且顺序一至
> db.stu.find({grade:{"redis" : 50, "java" : 60, "js" : 70, "zk" : 80}});
{ "_id" : ObjectId("5dccc542787a8449d387b655"), "name" : "111", "age" : 1, "grade" : { "redis" : 50, "java" : 60, "js" : 70, "zk" : 80 } }

# 基于复合属性当中的指定值查找时, 名称必须用双引号
> db.stu.find({"grade.redis":50})
{ "_id" : ObjectId("5dccc542787a8449d387b655"), "name" : "111", "age" : 1, "grade" : { "redis" : 50, "java" : 60, "js" : 70, "zk" : 80 } }
> db.stu.find({"grade.java":60})
{ "_id" : ObjectId("5dccc542787a8449d387b655"), "name" : "111", "age" : 1, "grade" : { "redis" : 50, "java" : 60, "js" : 70, "zk" : 80 } }

> db.stu.find({"grade.java":{$gt:60}})
{ "_id" : ObjectId("5dccc542787a8449d387b656"), "name" : "222", "age" : 2, "grade" : { "redis" : 52, "java" : 62, "js" : 90, "zk" : 81 } }
{ "_id" : ObjectId("5dccc542787a8449d387b657"), "name" : "333", "age" : 3, "grade" : { "redis" : 76, "java" : 63, "js" : 89, "zk" : 34 } }

数组查询:

# 集合subject包含subjects数组
> db.subject.find();
{ "_id" : ObjectId("5dccc6df787a8449d387b659"), "subjects" : [ "redis", "java", "js" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65a"), "stu" : "222", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65b"), "stu" : "333", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65c"), "stu" : "444", "subjects" : [ "redis", "java", "js", "zk" ] }

#查询无结果
> db.subject.find({subjects:["redis","java"]})
#查询无结果
> db.subject.find({subjects:["redis","java","zk","js"]})

# 与嵌套查询一样,数组查询必须是所有的值 并且顺序一至
> db.subject.find({subjects:["redis","java","js","zk"]})
{ "_id" : ObjectId("5dccc6df787a8449d387b65a"), "stu" : "222", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65b"), "stu" : "333", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65c"), "stu" : "444", "subjects" : [ "redis", "java", "js", "zk" ] }
> db.subject.find({subjects:["redis","java","js"]})
{ "_id" : ObjectId("5dccc6df787a8449d387b659"), "subjects" : [ "redis", "java", "js" ] }

# $all 匹配数组中包含该两项的值。注:顺序不作要求
> db.subject.find({subjects:{"$all":["redis","java","js"]}})
{ "_id" : ObjectId("5dccc6df787a8449d387b659"), "subjects" : [ "redis", "java", "js" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65a"), "stu" : "222", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65b"), "stu" : "333", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65c"), "stu" : "444", "subjects" : [ "redis", "java", "js", "zk" ] }
> db.subject.find({subjects:{"$all":["redis","zk","js"]}})
{ "_id" : ObjectId("5dccc6df787a8449d387b65a"), "stu" : "222", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65b"), "stu" : "333", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65c"), "stu" : "444", "subjects" : [ "redis", "java", "js", "zk" ] }

# 简化数组查询
> db.subject.find({subjects:"zk"})
{ "_id" : ObjectId("5dccc6df787a8449d387b65a"), "stu" : "222", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65b"), "stu" : "333", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65c"), "stu" : "444", "subjects" : [ "redis", "java", "js", "zk" ] }

# 简化数组查询 ,匹配数组中存在任意一值。与$all相对应
> db.subject.find({subjects:{"$in":["redis","zk","js"]}})
{ "_id" : ObjectId("5dccc6df787a8449d387b659"), "subjects" : [ "redis", "java", "js" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65a"), "stu" : "222", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65b"), "stu" : "333", "subjects" : [ "redis", "java", "js", "zk" ] }
{ "_id" : ObjectId("5dccc6df787a8449d387b65c"), "stu" : "444", "subjects" : [ "redis", "java", "js", "zk" ] }

数组嵌套查询:

# subjects集合包含嵌套数组
> db.subject2.find();
{ "_id" : "001", "stu" : "111", "subjects" : [ { "name" : "redis", "hour" : 12 }, { "name" : "dubbo", "hour" : 120 }, { "name" : "zookeper", "hour" : 56 } ] }
{ "_id" : "002", "stu" : "222", "subjects" : [ { "name" : "java", "hour" : 120 }, { "name" : "mysql", "hour" : 10 }, { "name" : "oracle", "hour" : 30 } ] }
{ "_id" : "003", "stu" : "333", "subjects" : [ { "name" : "mysql", "hour" : 12 }, { "name" : "html5", "hour" : 120 }, { "name" : "netty", "hour" : 56 } ] }
{ "_id" : "004", "stu" : "444", "subjects" : [ { "name" : "redis", "hour" : 12 }, { "name" : "dubbo", "hour" : 120 }, { "name" : "netty", "hour" : 56 } ] }

# 基础查询 ,必须查询全部,且顺序一至
> db.subject2.find({subjects:{"name" : "redis", "hour" : 12}})
{ "_id" : "001", "stu" : "111", "subjects" : [ { "name" : "redis", "hour" : 12 }, { "name" : "dubbo", "hour" : 120 }, { "name" : "zookeper", "hour" : 56 } ] }
{ "_id" : "004", "stu" : "444", "subjects" : [ { "name" : "redis", "hour" : 12 }, { "name" : "dubbo", "hour" : 120 }, { "name" : "netty", "hour" : 56 } ] }

# 指定查询第一个数组 课时大于12
> db.subject2.find({"subjects.0.hour":{$gt:12}})
{ "_id" : "002", "stu" : "222", "subjects" : [ { "name" : "java", "hour" : 120 }, { "name" : "mysql", "hour" : 10 }, { "name" : "oracle", "hour" : 30 } ] }

# 查询课时大于12的科目
> db.subject2.find({"subjects.hour":{$gt:12}})
{ "_id" : "001", "stu" : "111", "subjects" : [ { "name" : "redis", "hour" : 12 }, { "name" : "dubbo", "hour" : 120 }, { "name" : "zookeper", "hour" : 56 } ] }
{ "_id" : "002", "stu" : "222", "subjects" : [ { "name" : "java", "hour" : 120 }, { "name" : "mysql", "hour" : 10 }, { "name" : "oracle", "hour" : 30 } ] }
{ "_id" : "003", "stu" : "333", "subjects" : [ { "name" : "mysql", "hour" : 12 }, { "name" : "html5", "hour" : 120 }, { "name" : "netty", "hour" : 56 } ] }
{ "_id" : "004", "stu" : "444", "subjects" : [ { "name" : "redis", "hour" : 12 }, { "name" : "dubbo", "hour" : 120 }, { "name" : "netty", "hour" : 56 } ] }

# $elemMatch 元素匹配,指定属性满足,且不要求顺序一至
> db.subject2.find({subjects:{$elemMatch:{name:"redis",hour:12}}})
{ "_id" : "001", "stu" : "111", "subjects" : [ { "name" : "redis", "hour" : 12 }, { "name" : "dubbo", "hour" : 120 }, { "name" : "zookeper", "hour" : 56 } ] }
{ "_id" : "004", "stu" : "444", "subjects" : [ { "name" : "redis", "hour" : 12 }, { "name" : "dubbo", "hour" : 120 }, { "name" : "netty", "hour" : 56 } ] }

> db.subject2.find({subjects:{$elemMatch:{hour:12,name:"redis"}}})
{ "_id" : "001", "stu" : "111", "subjects" : [ { "name" : "redis", "hour" : 12 }, { "name" : "dubbo", "hour" : 120 }, { "name" : "zookeper", "hour" : 56 } ] }
{ "_id" : "004", "stu" : "444", "subjects" : [ { "name" : "redis", "hour" : 12 }, { "name" : "dubbo", "hour" : 120 }, { "name" : "netty", "hour" : 56 } ] }

# 数组中任意元素匹配 不限定在同一个对象当中
> db.subject2.find({"subjects.name":"mysql","subjects.hour":12})
{ "_id" : "003", "stu" : "333", "subjects" : [ { "name" : "mysql", "hour" : 12 }, { "name" : "html5", "hour" : 120 }, { "name" : "netty", "hour" : 56 } ] }
> db.subject2.find({"subjects.name":"mysql","subjects.hour":120})
{ "_id" : "002", "stu" : "222", "subjects" : [ { "name" : "java", "hour" : 120 }, { "name" : "mysql", "hour" : 10 }, { "name" : "oracle", "hour" : 30 } ] }
{ "_id" : "003", "stu" : "333", "subjects" : [ { "name" : "mysql", "hour" : 12 }, { "name" : "html5", "hour" : 120 }, { "name" : "netty", "hour" : 56 } ] }

 

删除文档

// 基于查找删除
db.emp.deleteOne({_id:1101})
// 删除整个emp集合
 db.emp.drop()
// 删除当前库,未使用use切换,则默认是test,使用db查看当前数据库
db.dropDatabase()

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值