文章目录
1. MongoDB数据库入门
1.1 服务器启动
1.1.1 数据库路径:
--dbpath “C:\\MongoDB\data\db”
1.1.2 日志路径:
--logpath “C:\\MongoDB\data\log\mongo.log”
在启动服务器时,在bin文件夹启动cmd,并输入以下指令
mongod.exe --dbpath “C:\\MongoDB\data\db” --logpath “C:\\MongoDB\data\log\mongo.log”
1.2 客户端启动
1.2.1 不指定端口(默认27017)
mongo.exe
1.2.2 指定端口
mongo.exe --port 27017
1.3 数据基本操作(增,删,改,査)
在这之前,我们需要了解一下内容:
MongoDB中包含多个数据库(database),一个数据库由多个集合(Collection) 构成,而一个集合可以由多个文档(document) 组成。
1.3.1 创建数据库
我们可以使用show dbs命令来查看所有数据库:
>show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
如果我们想要创建自己的数据库,那么使用use指令即可
>use DATABASE_NAME
创建完自己的数据库,我们可以使用以下指令为自己的数据库添加数据:
db.users.insert();
db.users.insertOne() //插入单个数据
db.users.insertMany() //插入多个数据
我们尝试使用第一条指令来插入一条数据,我们的数据库名为information:
>db.information.insert({name:"lilei",age:45,tags:["java","mysql","mongodb"],city:"hangzhou"})
WriteResult({ "nInserted" : 1 })
那么你为自己的数据库添加了第一条指令,让我们用 find() 指令来查看我们插入的数据,指令的基本形式为:
db.<数据库名>.find()
示例程序:
>db.information.find()
{ "_id" : ObjectId("5e679c41888d7e77c4f25192"), "name" : "lilei", "age" : 45, "tags" : [ "java", "mysql", "mongodb" ], "city" : "hangzhou" }
如果你觉得这样的显示不便于查看,那么可以使用 pretty() 指令来查看数据:
db.<数据库名>.find().pretty()
示例程序:
>db.information.find().prtty()
{
"_id" : ObjectId("5e679c41888d7e77c4f25192"),
"name" : "lilei",
"age" : 45,
"tags" : [
"java",
"mysql",
"mongodb"
],
"city" : "hangzhou"
}
1.3.1 删除数据库
删除数据库需要我们有以下几步:
-
查看所有数据库:
>show dbs admin 0.000GB config 0.000GB information 0.000GB local 0.000GB
-
切换到对应的数据库:
>use information switched to db information
-
使用 dopDatabase() 指令来删除对应数据库
>db.dropDatabase() { "dropped" : "information", "ok" : 1 }
-
删除后我们再来查看数据库:
>db.dropDatabase() >show dbs admin 0.000GB config 0.000GB local 0.000GB
此时我们看到对应的数据库已经删除。
1.3.3 创建集合
创建集合需要我们用到 createCollection() 指令,那么指令的基本形式为:
db.createCollection(name, options) //name is the collection name,options are optional parameters
options的参数有以下几种:
字段 | 类型 | 描述 |
---|---|---|
capped | 布尔 | (可选)如果为 true,则创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。当该值为 true 时,必须指定 size 参数。 |
autoIndexId | 布尔 | (可选)如为 true,自动在 _id 字段创建索引。默认为 false。 |
size | 数值 | (可选)为固定集合指定一个最大值,以千字节计(KB)。如果 capped 为 true,也需要指定该字段。 |
max | 数值 | (可选)指定固定集合中包含文档的最大数量。 |
在插入文档时,MongoDB首先检查固定集合的 size 字段,然后检查max字段。
创建集合有以下两种方式
-
mongodb自动创建集合,例如在上面的示例程序中:
>db.information.insert({name:"lilei",age:45,tags:["java","mysql","mongodb"],city:"hangzhou"}) WriteResult({ "nInserted" : 1 })
此时我们使用show collections或者show tables命令:
>show collections information
则可以看到,mongodb默认为我们创建了集合information
-
手动创建集合:
-
如果我们不指定options参数
>db.createCollection("test1") { "ok" : 1 }
查看集合
>show collections information test1
可以看到集合已经创建好
-
指定options参数
创建固定集合test2,整个集合空间大小6142800KB, 文档最大个数为5000个。
>db.createCollection("test2", { capped : true, autoIndexId : true, size : 6142800, max : 5000 } ) { "ok" : 1 }
查看集合
>show collections information test1 test2
-
1.3.4 删除集合
创建集合需要我们用到 drop() 指令,那么指令的基本形式为:
db.collection.drop()