MongoDB:简介及快速入门

x33g5p2x  于2022-03-02 转载在 Go  
字(10.4k)|赞(0)|评价(0)|浏览(308)

MongoDB:简介及快速入门

一、MongoDB简介

简介

MongoDB是用C++语言编写的非关系型数据库。MongoDB是一个基于分布式文件存储的数据库,它是一个介于关系数据库和非关系数据库之间的产品

特点是高性能、易部署、易使用,存储数据十分方便

主要特性有:

  • 模式自由
  • 面向集合存储,易于存储对象类型的数据
  • 支持动态查询
  • 支持完全索引,包含内部对象
  • 支付复制和故障恢复
  • 使用高效的二进制数据存储,包括大型对象
  • 文件存储格式为BSON(一种JSON的扩展)

基本概念

  1. 文档(document)是MongoDB中数据的基本单元,非常类似于关系型数据库系统中的行(但是比行要复杂的多)
  2. 集合(collection)就是一组文档,如果说MongoDB中的文档类似于关系型数据库中的行,那么集合就如同表
  3. MongoDB的单个计算机可以容纳多个独立的数据库,每一个数据库都有自己的集合和权限
  4. MongoDB自带简洁但功能强大的JavaScript shell,这个工具对于管理MongoDB实例和操作数据作用非常大
  5. 每一个文档都有一个特殊的键"_id",它在文档所处的集合中是唯一的,相当于关系数据库中的表的主键

数据类型

数据类型描述举例
null表示空值或者未定义的对象{“x”:null}
布尔值真或者假:true或者false{“x”:true}
32位整数shell是不支持该类型的,shell中默认会转换成64位浮点数
64位整数shell是不支持该类型的,shell中默认会转换成64位浮点数
64位浮点数shell中的数字就是这一种类型{“x”:3.14,“y”:3}
字符串UTF-8字符串{“foo”:“bar”}
符号shell不支持,shell会将数据库中的符号类型的数据自动转换成字符串
对象id文档的12字节的唯一id{“id”: ObjectId()}
日期从标准纪元开始的毫秒数{“date”:new Date()}
正则表达式文档中可以包含正则表达式,遵循JavaScript的语法{“foo”:/foobar/i}
代码文档中可以包含JavaScript代码{“x”:function() {}}
未定义undefined{“x”:undefined}
数组值的集合或者列表{“arr”: [“a”,“b”]}
内嵌文档文档可以作为文档中某个key的value{“x”:{“foo”:“bar”}}

MongoDB与MySQL对比

对比项mongodbmysql
集合table
表中的一行数据文档document一条记录record
表字段键key字段field
字段值值value值value
主外键pk,fk
灵活度扩展性极高

二、MongoDB安装

docker安装mongodb

三、基本命令

使用命令行进入容器:

docker exec -it mongo /bin/bash

连接mongo:

mongo -u root -p root112211 admin

展示数据库、数据表

# 展示所有数据库:
$ show dbs

# 进入dbname数据库,大小写敏感(如果存在就进入,不存在就创建):
# 注意:使用命令use mydb1创建数据库后,并没有真正生成对应的数据文件,如果此时退出,此数据库将被删除,只有在此数据库中创建集合后,才会真正生成数据文件
$ use dbname

# 显示数据库中的集合:
$ show collections

# 查看当前所在数据库
$ db

创建&新建

# 显示创建集合
> db.createCollection('集合名称')
{ "ok" : 1 }

# 创建名为users的集合,并新增了一条数据
> db.users.save({"name":"lecaf"})
WriteResult({ "nInserted" : 1 })

# 在users集合中插入一条新数据,如果没有users这个集合,mongodb会自动创建
> db.users.insert({"name":"ghost", "age":10}) 
WriteResult({ "nInserted" : 1 })

# 查看结果
> db.users.find()
{ "_id" : ObjectId("621f06699be2560f8459610a"), "name" : "lecaf" }
{ "_id" : ObjectId("621f07109be2560f8459610b"), "name" : "zhangsan", "age" : 10 }

save()和insert()也存在着些许区别:

  • 若新增的数据主键已经存在,insert()会不做操作并提示错误,而save() 则更改原来的内容为新内容
存在数据:{ _id : 1, " name " : " n1 "} ,_id是主键
insert({ _id : 1, " name " : " n2 " })    会提示错误
save({ _id : 1, " name " : " n2 " })     会把 n1 改为  n2 ,有update的作用。

3.2 版本后还有以下几种语法可用于插入文档:

db.collection.insertOne():向指定集合中插入一条文档数据
 db.collection.insertMany():向指定集合中插入多条文档数据
 
#  插入单条数据
> db.users.insertOne({"a":3})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("571a218011a82a1d94c02333")
}
#  插入多条数据
> db.users.insertMany([{"b":3},{"c":5}])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("571a22a911a82a1d94c02337"),
                ObjectId("571a22a911a82a1d94c02338")
        ]
}

删除

remove语法:

db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>
   }
)

参数说明:

  • query**:**(可选)删除的文档的条件
  • justOne : (可选)如果设为 true 或 1,则只删除一个文档
  • writeConcern:(可选)抛出异常的级别
# 删除users集合下所有数据
> db.users.remove({})

#  删除users集合下name=lecaf的数据
> db.users.remove({"name": "lecaf"})

# 删除集合users
> db.users.drop()或db.runCommand({"drop","users"})

# 删除当前数据库或者使用,db.dropDatabase()
> db.runCommand({"dropDatabase": 1})

deleteOne() 和 deleteMany()

remove() 方法已经过时了,现在官方推荐使用 deleteOne() 和 deleteMany() 方法

# 删除集合下全部文档
> db.users.deleteMany({})

# 删除 status 等于 A 的全部文档
> db.users.deleteMany({ status : "A" })

# 删除 status 等于 D 的一个文档
> db.users.deleteOne( { status: "D" } )

修改

update语法:db.collection.update(criteria,objNew,upsert,multi)

参数说明:

  • criteria:用于设置查询条件的对象(必填)({},表示更新所有)

  • objNew:用于设置更新内容的对象(必填)

  • upsert:如果记录已经存在,更新它,否则新增一个记录,取值为0或1(true为插入,默认是false,不插入)

  • multi:如果有多个符合条件的记录,是否全部更新,取值为0或1(mongodb 默认是false,只更新找到的第一条记录)
    注意:默认情况下,只会更新第一个符合条件的记录

  • 一般情况下后两个参数分别为0,1 ,即:db.collection.update(criteria,objNew,0,1)

  • db.users.update({“name”:“lecaf”}, {“age”:10})

修改name=lecaf的数据为age=10,第一个参数是查找条件,第二个参数是修改内容

  • 除了主键,其他内容会被第二个参数的内容替换,主键不能修改

在3.2版本开始,MongoDB提供以下更新集合文档的方法:

db.collection.updateOne() 向指定集合更新单个文档

db.collection.updateMany() 向指定集合更新多个文档
  • 首先我们在test集合里插入测试数据
> use test
switched to db test

> db.test_collection.insert( [

{"name":"abc","age":"25","status":"zxc"},

{"name":"dec","age":"19","status":"qwe"},

{"name":"asd","age":"30","status":"nmn"},

] )

> db.test_collection.find()
{ "_id" : ObjectId("621f0eec9be2560f8459610f"), "name" : "abc", "age" : "25", "status" : "zxc" }
{ "_id" : ObjectId("621f0eec9be2560f84596110"), "name" : "dec", "age" : "19", "status" : "qwe" }
{ "_id" : ObjectId("621f0eec9be2560f84596111"), "name" : "asd", "age" : "30", "status" : "nmn" }
  • 更新单个文档
> db.test_collection.updateOne({"name":"abc"},{$set:{"age":"28"}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

> db.test_collection.find()
{ "_id" : ObjectId("621f0eec9be2560f8459610f"), "name" : "abc", "age" : "28", "status" : "zxc" }
{ "_id" : ObjectId("621f0eec9be2560f84596110"), "name" : "dec", "age" : "19", "status" : "qwe" }
{ "_id" : ObjectId("621f0eec9be2560f84596111"), "name" : "asd", "age" : "30", "status" : "nmn" }
  • 更新多个文档
> db.test_collection.updateMany({"age":{$gt:"10"}},{$set:{"status":"xyz"}})
{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }

> db.test_collection.find()
{ "_id" : ObjectId("621f0eec9be2560f8459610f"), "name" : "abc", "age" : "28", "status" : "xyz" }
{ "_id" : ObjectId("621f0eec9be2560f84596110"), "name" : "dec", "age" : "19", "status" : "xyz" }
{ "_id" : ObjectId("621f0eec9be2560f84596111"), "name" : "asd", "age" : "30", "status" : "xyz" }

更新集合中的文档,使用 $inc 将集合中name为user1的age加1,其它键不变, $inc表示使某个键值加减指定的数值

更新集合中的文档, $unset 用来删除某个键,例如删除name为user1的文档中的address键,可以使用命令:

> db.c1.update({name:”user1”},{$unset:{address:1}},0,1)

查找

# 查找users集合中所有数据
> db.users.find()

# 查找users集合中的第一条数据
> b.users.findOne(条件)
条件查找
# 查找key=value的数据
> db.collection.find({ "key" : value })

# key > value
> db.collection.find({ "key" : { $gt: value } }) 

# key < value
> db.collection.find({ "key" : { $lt: value } })

# key >= value
> db.collection.find({ "key" : { $gte: value } })

# key <= value
> db.collection.find({ "key" : { $lte: value } })    

# value1 < key <value2
> db.collection.find({ "key" : { $gt: value1 , $lt: value2 } })

# key <> value
> db.collection.find({ "key" : { $ne: value } })

# 取模运算,条件相当于key % 10 == 1 即key除以10余数为1的
> db.collection.find({ "key" : { $mod : [ 10 , 1 ] } })  

# 不属于,条件相当于key的值不属于[ 1, 2, 3 ]中任何一个
> db.collection.find({ "key" : { $nin: [ 1, 2, 3 ] } })  

# 属于,条件相当于key等于[ 1, 2, 3 ]中任何一个
> db.collection.find({ "key" : { $in: [ 1, 2, 3 ] } })

# 或 (注意:MongoDB 1.5.3后版本可用),符合条件a=1的或者符合条件b=2的数据都会查询出来
> db.collection.find({ $or : [{a : 1}, {b : 2} ] })  

#数量,条件相当于key的值的数量是1(key必须是数组,一个值的情况不能算是数量为1的数组)
> db.collection.find({ "key" : { $size: 1 } })    

# 传入多个键(key),每个键(key)以逗号隔开,类似常规 SQL 的 AND 条件
> db.collection.find({key1:value1, key2:value2}).pretty()
and 和or联合使用
> db.test_collection.find({"age": {$gt:"20"}, $or: [{"status": "xyz"}]}).pretty()

{
	"_id" : ObjectId("621f0eec9be2560f8459610f"),
	"name" : "abc",
	"age" : "28",
	"status" : "xyz"
}
{
	"_id" : ObjectId("621f0eec9be2560f84596111"),
	"name" : "asd",
	"age" : "30",
	"status" : "xyz"
}
exists

语法:db.collection.find({ "key" : { $exists : true|false } })

查询集合中的文档 ,$exists,用于查询集合中存在某个键的文档不存在某个键的文档

例如查询customer集合中存在name键的所有文档,可以使用 db.customer.find({name:{$exists:1}}),

$exists:1表示真,指存在

$exists:0表示假,指不存在

排序

# 这里的1代表升序,-1代表降序
> db.collection.find().sort({ "key1" : -1 ,"key2" : 1 })

其他

#  控制返回结果数量,如果参数是0,则当作没有约束,limit()将不起作用
> db.collection.find().limit(5)

# 控制返回结果跳过多少数量,如果参数是0,则当作没有约束,skip()将不起作用,或者说跳过了0条
> db.collection.find().skip(5) 

# 可用来做分页,跳过5条数据再取5条数据
> db.collection.find().skip(5).limit(5)

# count()返回结果集的条数
> db.collection.find().count(true)

# 加入skip()和limit()这两个操作时,获得实际返回的结果数,需要一个参数true,否则返回的是符合查询条件的结果总数
> db.collection.find().skip(5).limit(5).count(true)

四、Springboot整合mongodb

依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

配置文件

spring.data.mongodb.uri=mongodb://admin:admin@127.0.0.1:27017/test

spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test,其中name是用户名,pass是密码

添加

插入一条

@Test
    public void testSave() {
        User save = mongoTemplate.save(new User("zhangsan", "30", "hhh"));
        System.out.println(save);
    }

批量插入

@Test
    public void testSaveByList() {
        List<User> userList = ListUtil.of(new User("lisi", "30", "hhh"), new User("wangwu", "29", "hhh"));
        Collection<User> users = mongoTemplate.insertAll(userList);
        System.out.println(users);
    }

更新

更新一条

@Test
    public void testUpdateOne(){
        Query query = new Query(Criteria.where("name").is("wangwu"));
        Update update = new Update().set("name", "zhaoliu").set("age", "31").set("address", "wuhan");
        mongoTemplate.updateFirst(query, update, User.class);
    }

批量更新

@Test
    public void testUpdateMany(){
        Query query = new Query(Criteria.where("age").is("31"));
        Update update = new Update().set("age", "40");
        mongoTemplate.updateMulti(query, update, User.class);
    }

查询

@Test
    public void testFind(){
        Query query = new Query(Criteria.where("name").is("zhangsan"));
        List<User> userList = mongoTemplate.find(query, User.class);
        System.out.println(userList);
    }

删除

删除数据

@Test
    public void testDelete(){
        Query query = new Query(Criteria.where("name").is("zhangsan"));
        mongoTemplate.remove(query,User.class);
    }

删除集合

@Test
    public void testDeleteDoc(){
        mongoTemplate.dropCollection(User.class);
    }

相关文章