当前位置:网站首页>mongodb(快速上手)(一)
mongodb(快速上手)(一)
2022-07-05 16:57:00 【进击的北极熊】
资料地址:
链接:https://pan.baidu.com/s/1DxgX3RCvWfaKzziHG8IHZQ
提取码:3452
gitee地址
https://gitee.com/liushanshan126/mongodb-test
一、mongdb相关概念
1、mysql和mongdb对比


2、bson(mongdb存储结构,与json类似)
- Bson中,除了基本的JSON类型:string,integer,boolean,double,null,array和object
- mongo还使用了特殊的数据类型。这些类型包括date,object id,binary data,regular expression
和code。每一个驱动都以特定语言的方式实现了这些类型,查看你的驱动的文档来获取详细信息。
二、单机部署
1、安装压缩文件,并且创建data/db文件
2、单机启动命令
进入bin文件夹中,cmd控制台,输入命令:
mongod–dbpath=…\data\db
三、基本常用命令
1、创建、显示数据库

注意:创建数据库,但是这个数据库没有集合(表)的时候,只会存在于内存中,只有当当前的数据库中有集合的时候才会实例化到磁盘中
2、删除
进入需要删除的数据库,然后执行
db.dropDatabase()
3 、插入数据
db.comment.insert({“articleid”:“100000”,“content”:“今天天气真好,阳光明媚”,“userid”:“1001”,“nickname”:“Rose”,“createdatetime”:newDate(),“likenum”:NumberInt(10),“state”:null})
3、查询db.document.find({},{}):document为表;第一个大括号:查询条件,相当于where后面的条件;第二个大括号:显示哪些字段,相当于select后面的查询字段
例如: db.article.findOne({articleid:‘12222’}, {userid:1, nickname:1}) 查询字段articleid为12222的数据,且只拿出userid,nickname, _id(默认)字段
4、更新
4.1 、 普通更新(局部更新$set)
db.article.update({_id:“2”},{$set:{likenum:NumberInt(889)}})
4.2 列值增加 (数字 + n) $inc
db.article.update({_id:“3”},{$inc:{likenum:NumberInt(1)}})
5、删除文档

6、排序 sort
sort() 方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序排列,而 -1 是用于降序排列。
db.COLLECTION_NAME.find().sort({KEY:1})
skip、limit、sort的执行顺序
跟mysql一样,先执行sort,在执行skip,最后执行limit
7、正则表达

8、比较查询(大于,小于,大于等于,小于等于,不等于)

9、包含(in),不包含(nin)
in:db.comment.find({userid:{ KaTeX parse error: Expected 'EOF', got '}' at position 19: …["1003","1004"]}̲}) nin:db.comme…nin:[“1003”,“1004”]}})
10、条件连接。or和and的使用

总结
选择切换数据库:usearticledb
插入数据:db.comment.insert({bson数据})
查询所有数据:db.comment.find();
条件查询数据:db.comment.find({条件})
查询符合条件的第一条记录:db.comment.findOne({条件})
查询符合条件的前几条记录:db.comment.find({条件}).limit(条数)
查询符合条件的跳过的记录:db.comment.find({条件}).skip(条数)
修改数据:db.comment.update({条件},{修改后的数据})或db.comment.update({条件},{ KaTeX parse error: Expected '}', got 'EOF' at end of input: …t.update({条件},{ inc:{自增的字段:步进值}})
删除数据:db.comment.remove({条件})
统计查询:db.comment.count({条件})
模糊查询:db.comment.find({字段名:/正则表达式/})
条件比较运算:db.comment.find({字段名:{$gt:值}})包含查询:db.comment.find({字段名:{ KaTeX parse error: Expected 'EOF', got '}' at position 11: in:[值1,值2]}̲})或db.comment.f…nin:[值1,值2]}})
条件连接查询:db.comment.find({ KaTeX parse error: Expected 'EOF', got '}' at position 18: …d:[{条件1},{条件2}]}̲)或db.comment.fi…or:[{条件1},{条件2}]})
四、索引
1、类型
单字段索引、复合索引、其他索引
2、索引的查看、创建、删除
查看:db.collection.getIndexes()
创建:
单字段索引:db.comment.createIndex({userid:1})
复合索引:db.comment.createIndex({userid:1,nickname:-1})
删除:
单个删除:db.comment.dropIndex({userid:1})
删除所有索引:db.collection.dropIndexes()
3、使用索引作为条件,查询字段也为索引,则不查集合,直接查询索引

五、java实际操作mongodb
1、引入依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/>
<!--lookupparentfromrepository-->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--连接mongodb的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
2、dao

3、实体类

4、service
package com.bear.service;
import com.bear.dao.CommentRepository;
import com.bear.pojo.Comment;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Optional;
/** * <简述> * <详细描述> * * @author LiuShanshan * @version $Id$ */
@Service
public class CommentService {
@Resource
private CommentRepository commentRepository;
/** *<简述> 增加 *<详细描述> * @author Liushanshan * @param comment * @return void */
public void saveComment(Comment comment){
Comment save = commentRepository.save(comment);
System.out.println(save);
}
// 删
public void delete(String id){
commentRepository.deleteById(id);
}
// 改
public void update (Comment comment){
commentRepository.save(comment);
}
// 查
public Comment select (String id){
Optional<Comment> byId = commentRepository.findById(id);
Comment comment = byId.get();
return comment;
}
}
5、测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes=MongodbApplication.class)
public class Test {
@Autowired
private CommentService commentService;
// 保存
@org.junit.Test
public void saveTest(){
Comment comment = new Comment();
comment.setArticleid("100000");
comment.setContent("测试添加的数据");
comment.setCreatedatetime(LocalDateTime.now());
comment.setUserid("1003");
comment.setNickname("凯撒大帝");
comment.setState("1");
comment.setLikenum(0);
comment.setReplynum(0);
commentService.saveComment(comment);
}
// 查询
@org.junit.Test
public void select(){
Comment select = commentService.select("62bd78cc4e03471050ba849e");
System.out.println(select);
}
// 更新
@org.junit.Test
public void update(){
Comment select = commentService.select("62bd78cc4e03471050ba849e");
select.setUserid("234234234");
commentService.update(select);
}
// 删除
}
6、分页条件查询

6.1 分页条件查询2.0

6.2 MongoTemplate的使用(***)

边栏推荐
- CMake教程Step5(添加系统自检)
- Embedded-c Language-2
- Use JDBC technology and MySQL database management system to realize the function of course management, including adding, modifying, querying and deleting course information.
- MySql 查询符合条件的最新数据行
- Using C language to realize palindrome number
- Embedded UC (UNIX System Advanced Programming) -1
- 腾讯音乐上线新产品“曲易买”,提供音乐商用版权授权
- Embedded -arm (bare board development) -1
- Embedded-c Language-1
- Mysql5.6 parsing JSON strings (supporting complex nested formats)
猜你喜欢

激动人心!2022开放原子全球开源峰会报名火热开启!
Tips for extracting JSON fields from MySQL

33: Chapter 3: develop pass service: 16: use redis to cache user information; (to reduce the pressure on the database)

Browser rendering principle and rearrangement and redrawing

Deeply cultivate 5g, and smart core continues to promote 5g applications

Alpha conversion from gamma space to linner space under URP (II) -- multi alpha map superposition

Kafaka技术第一课

CMake教程Step1(基本起点)

北京内推 | 微软亚洲研究院机器学习组招聘NLP/语音合成等方向全职研究员

Machine learning compilation lesson 2: tensor program abstraction
随机推荐
基于Redis实现延时队列的优化方案小结
华为云云原生容器综合竞争力,中国第一!
WebApp开发-Google官方教程
Is it safe to open an account for digging wealth stocks? How is it safe to open a stock account?
一文了解MySQL事务隔离级别
深入理解Redis内存淘汰策略
Machine learning 02: model evaluation
【testlink】TestLink1.9.18常见问题解决方法
CMake教程Step3(添加库的使用要求)
Q2 encryption market investment and financing report in 2022: gamefi becomes an investment keyword
Cmake tutorial step6 (add custom commands and generate files)
Little knowledge about C language (array and string)
腾讯音乐上线新产品“曲易买”,提供音乐商用版权授权
Embedded UC (UNIX System Advanced Programming) -1
ICML 2022 | Meta提出魯棒的多目標貝葉斯優化方法,有效應對輸入噪聲
dried food! Semi supervised pre training dialogue model space
叩富网开期货账户安全可靠吗?怎么分辨平台是否安全?
[wechat applet] read the life cycle and route jump of the applet
Is it safe and reliable to open futures accounts on koufu.com? How to distinguish whether the platform is safe?
First day of learning C language