当前位置:网站首页>MongDB学习笔记
MongDB学习笔记
2022-07-05 14:35:00 【JavaSupeMan】
1.NoSQL的特点
是一种非关系型数据库,文档形式的存储
特点:文档数据库将数据以文档的形式存储,BSON格式,类似JSON,是一系列数据项的集合。每个数据项都有一个名称与对应的值,值既可以是简单的数据类型,如字符串/数字/日期等。也可以是复杂的类型。
==优点:==数据结构要求不严格,表结构可变,不需要像关系型数据库一样需要预先定义表结构
==缺点:==查询性能不高,缺乏统一的查询语法
应用场景:日志,web应用等
启动命令:
--dbpath: 指定数据文件存放目录
--logpath:指定日志文件,注意是指定文件不是目录
--logappend:使用追加的方式记录日志
--port:指定端口,默认为27017
--bind_ip:绑定服务IP,若绑定127.0.0.1,则只能本机访问,默认为本机地址
mongod --dbpath D:\MongDB\data\db
3.安全认证
创建管理员账号
#设置管理员用户名密码需要切换到admin库
use admin
#创建管理员
db.createUser({
user:"fox",pwd:"fox",roles:["root"]})
#查看所有用户信息
show users
#删除用户
db.dropUser("fox")
#使用用户进行登录,默认到admin库
mongo -ufox -pfox --authenticationDatabase=admin
4.MongoDB文档操作
1.插入文档
2.查询文档
db.collection.find(query,projection)
db.collection.findOne(query,projection)
*query:可选,使用查询操作符指定查询条件
*projection:可选,使用投影操作符指定返回的键
查询对照表
例:
例:
查出库users中所有数据
db.users.find()
条件查询,查询user值为root的
db.users.find({user:“root”})
查询某个值大于某个数的值
db.users.find({age:{$gt:60}})
查询出第一条
db.users.findOne()
排序&分页
在MongoDB中使用sort()方法对数据进行排序
#指定按收藏数(favCount)降序返回 -1表示降序 表示升序
favCount type都是字段名
db.books.find({
type:"travel"}).sort({
favCount:-1})
分页查询:通过skip和limit去实现,skip表示指定跳过记录数,limit表示限定返回结果数量
例:
db.books.find().skip().limit(5)
3.更新文档
可以用update命令对指定的数据进行更新,命令格式如下:
db.collection.update(query,update,options)
db.collection.updateOne(query,update,options) //更新单个文档 相当于 multi属性为true
db.collection.updateMany(query,update,options) //更新多个文档
db.collection.replaceOne(query,update,options) //替换单个文档
# 属性解释:
# query :描述更新的查询条件
# update:描述更新的动作及新的内容
# options:描述更新的选项
# - upsert:可选,如果不存在update的记录,是否插入新的记录。默认false,不插入
- multi:可选,是否按条件查询出的多条记录全部更新。默认false,只更新找到的第一条记录
- writeConcern:可选,决定一个写操作落到多少个节点上才算成功(类似于事务操作)
update操作符如下:
例:
db.books.update({
type:"novel"},{
$Set:{
publishedDate:new Date()}},{
"multi":true})
注意:如果udate命令中的更新描述不包含任何操作符,那么MongoDB会实现文档的replace语义
例:
db.books.update({
type:"novel"},{
age:"1"})
会先找到type为novel的数据,然后它的内容被全部替换,替换的只剩 age:1
findAndModify命令:
查找并更新,只能操作单文档,不能操作多文档
格式:
例:增加new :true,会返回更新后的值,false返回更新前的值
db.books.findAndModify({
query:{
},update:{
}},new :true)
findOneAndUpdate: 更新单个文档并返回更新前(或更新后)的文档
findOneAndReplace:替换单个文档并返回替换前(或替换后)的文档
4.删除文档
remove命令
例:
例:
db.books.remove({
age:28}) //删除age等于28 的记录
db.books.remove({
age:{
$lt:25}}) //删除age小于25的记录
db.books.remove({
}) //删除所有记录
假如符合条件的有多个,但是只删除第一个,则需要制定justOne的参数,格式如下
例:
例:
db.books.remove({
age:28},true)
delete命令:
官方推荐使用deleteOne()和deleteMany()方法删除稳定,语法格式如下:
例:
db.books.deleteMany({
}) //删除集合下全部文档
db.books.deleteMany({
type:"novel"}) //指定条件的数据全部删除
db.books.deleteOne({
type:"novel"}) //指定条件的数据,只删除第一个
如果需要返回被删除的文档
命令:findOneAndDelete
例:
db.books.findOneAndDelete({
type:"novel"}) //删除集合下全部文档
MongoDB整合SpringBoot
1引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2.yml文件配置
spring:
data:
mongodb:
uri: mongodb://fox:[email protected]:27017/user?authSource=admin
#uri等同于下面的配置
# database: user
# host: 127.0.0.1
# port: 27017
# username: fox
# password: fox
# authentication-database: admin
3.注入bean
@Autowired
MongoTemplate mongoTemplate;
4.使用
1.增删改集合
//集合的操作
@RequestMapping("/test1")
public void ok(){
//判断集合是否存在
boolean flag = mongoTemplate.collectionExists("emp");
if(flag){
//删除集合
mongoTemplate.dropCollection("emp");
}
//创建集合
MongoCollection<Document> emp1 = mongoTemplate.createCollection("emp");
}
//文档的查询操作
@RequestMapping("/test2")
public void test2(){
//=============普通查询====================
//查询出所有文档
List<User> list = mongoTemplate.findAll(User.class);
//根据ID查询
User us = mongoTemplate.findById(1, User.class);
//查询结果是多个,返回其中第一个
User u = mongoTemplate.findOne(new Query(), User.class);
//=============条件查询=====================
//构建查询条件
Query query1 = new Query(Criteria.where("salary").gte(8000));
Query query2 = new Query(Criteria.where("salary").gte(8000).lt(10000));
Query query3 = new Query(Criteria.where("name").regex("张")); //模糊匹配
//==============多条件查询===================
Criteria criteria1 = new Criteria();
Criteria criteria2 = new Criteria();
//and的条件
criteria1.andOperator(Criteria.where("age").gt(25),Criteria.where("salary").gt(8000));
//or的条件
criteria1.orOperator(Criteria.where("age").gt(25),Criteria.where("salary").gt(8000));
Query query = new Query(criteria1);
//sort排序
query.with(Sort.by(Sort.Order.desc("salary")));
//分页
query.skip(1).limit(10);
//查询出所有文档,第三个参数是集合名
List<User> list = mongoTemplate.findAll(query, TestUser.class, "test2");
}
//文档的更新操作
@RequestMapping("/test3")
public void test3(){
//先查询出要修改的
Query query = new Query(Criteria.where("salary").gte(8000));
User u = mongoTemplate.findOne(query, User.class);
Update update = new Update();
update.set("name","张三");
//UpdateResult()
//UpdateFirst()更新满足条件的第一条记录
//UpdateMulti()更新所有满足条件的记录
//upsert() 没有符合条件的记录则插入数据
UpdateResult updateResult = mongoTemplate.upsert(query, update, User.class);
//返回修改的记录数
System.out.println(updateResult.getModifiedCount());
}
2.查询
使用bson当作查询条件进行查询
//1.构造查询条件
Bson filters = Filters.and(
Filters.eq("deviceId", warningEvent.getDeviceId()),
Filters.gte("date", strTime.getTime()),
Filters.lte("date", endTime.getTime()),
Filters.eq("lastUpdateTime", DateUtil.format(updateDate, "yyyy-MM-dd HH:mm"))
);
//2.指定字段排序,升序或者降序
Bson sort = Sorts.ascending("name");
// Bson sort = Sorts.descending("name");
//3.指定返回字段
List<String> list = new ArrayList<>();
list.add("name");
list.add("age");
// Inclusion 包含了指定的字段和(隐式的)_id字段
// Exclusion 包含了指定的字段和(隐式的)_id字段
Bson fields = Projections.fields(Projections.include(list));
//4.去指定集合中进行查询
MongoCursor<Document> mongoCursor = mongoTemplate.getCollection("weatherall").find(filters).projection(fields).sort(sort).iterator();
while (mongoCursor.hasNext()) {
Document document = mongoCursor.next();
//3.根据字段名获取数据
wdspList.add(document.getDouble("name"));
wdirList.add(document.getDouble("age"));
//document.getInteger()
lstDate.add(DateUtil.format(new Date(document.getLong("date")), "yyyy-MM-dd HH:mm"));
}
边栏推荐
- 做自媒体视频二次剪辑,怎样剪辑不算侵权
- Section - left closed right open
- There is a powerful and good-looking language bird editor, which is better than typora and developed by Alibaba
- C语言中限定符的作用
- Mysql database installation tutorial under Linux
- R language ggplot2 visualization: visual line graph, using legend in theme function The position parameter defines the position of the legend
- Two policemen were shot dead in a "safety accident" in Philadelphia, USA
- Thymeleaf th:with局部变量的使用
- 日化用品行业智能供应链协同系统解决方案:数智化SCM供应链,为企业转型“加速度”
- 网上电子元器件采购商城:打破采购环节信息不对称难题,赋能企业高效协同管理
猜你喜欢
PyTorch二分类时BCELoss,CrossEntropyLoss,Sigmoid等的选择和使用
freesurfer运行完recon-all怎么快速查看有没有报错?——核心命令tail重定向
Countermeasures of enterprise supply chain management system in UCA Era
安装配置Jenkins
Which Internet companies are worth going to in Shenzhen for software testers [Special Edition for software testers]
Pointer operation - C language
Topology可视化绘图引擎
Implement a blog system -- using template engine technology
乌卡时代下,企业供应链管理体系的应对策略
CyCa children's physical etiquette Ningbo training results assessment came to a successful conclusion
随机推荐
Principle and performance analysis of lepton lossless compression
Structure - C language
基于TI DRV10970驱动直流无刷电机
Thymeleaf 常用函数
PostgreSQL 13 installation
Intelligent supply chain collaboration system solution for daily chemical products industry: digital intelligent SCM supply chain, which is the "acceleration" of enterprise transformation
一网打尽异步神器CompletableFuture
LeetCode_ 67 (binary sum)
矩阵链乘 - 动态规划实例
面试突击62:group by 有哪些注意事项?
Is the securities account given by the head teacher of qiniu school safe? Can I open an account?
APR protocol and defense
SaaS multi tenant solution for FMCG industry to build digital marketing competitiveness of the whole industry chain
循环不变式
The forked VM terminated without saying properly goodbye
leetcode:881. 救生艇
Online electronic component purchasing Mall: break the problem of information asymmetry in the purchasing process, and enable enterprises to effectively coordinate management
有一个强大又好看的,赛过Typora,阿里开发的语雀编辑器
网上电子元器件采购商城:打破采购环节信息不对称难题,赋能企业高效协同管理
通过npm 或者 yarn安装依赖时 报错 出现乱码解决方式