SQL术语 | MongoDB术语 | 说明 |
---|---|---|
database | database | 数据库 |
table | collection | 数据库表/集合 |
row | document | 数据记录行/文档 |
column | field | 数据字段/域 |
index | index | 索引 |
table joins | 表连接,MongoDB不支持 | |
primary key | primary key | 主键,MongoDB自动将_id字段设置为主键 |
注意
#拉取镜像
docker pull mongo:latest
#创建和启动容器
docker run -d --restart=always -p 27017:27017 --name mymongo -v /data/db:/data/db -d mongo
#进入容器
docker exec -it mymongo/bin/bash
#使用MongoDB客户端进行操作
mongo
#查询所有的数据库
show dbs
db.help()
use 数据库名
show dbs
db.getName()
db.stats()
db.version()
db.getMongo
db.dropDatabase()
db.createCollection( "集合名")
show collections
db.getCollection("集合名")
db.printCollectionStats()
db.集合名.drop()
db.集合名.save({name:'zhangsan',age:21,sex:true})
db.集合名.find()
db.User.find({name:"zhangsan"})
相当于
select * from User where name = 'zhangsan';
db.User.find({age:21}, {'name':1, 'age':1})
相当于
select name, age from User where age = 21;
db.User.find().sort({age:1})
相当于
select * from User order by age;
db.User.find().skip(0).limit(3)
相当于
select * from User skip 2 limit 3;
db.User.find({age:{$in:[21,26,32]}})
相当于
select * from User where age in (21, 26, 32);
db.User.find({age:{$gt:20}}).count()
相当于
select count(*) from User where age >20;
db.User.find({$or:[{age:21}, {age:28}]})
相当于
select * from User where age = 21 or age = 28
db.User.find({name:"zs", age:28})
相当于
select * from User where name ='zs' and age = 28;
db.User.update({name:"zhangsan"}, {$set:{age:100, sex:0}})
相当于
update Userset age = 100, sex = 0 where name = 'user1'
根据id删除
db.User.remove(id)
删除所有
db.User.remove({})
表达式 | 描述 | 实例 |
---|---|---|
$sum | 计算总和 | db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$sum : “$likes”}}}]) |
$avg | 计算平均值 | db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$avg : “$likes”}}}]) |
$min | 获取集合中所有文档对应值得最小值 | db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$min : “$likes”}}}]) |
$max | 获取集合中所有文档对应值得最大值 | db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$max : “$likes”}}}]) |
db.User.createIndex({"name":1})
1、创建SpringBoot工程
2、导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>2.6.6</version>
</dependency>
3、配置文件application.yml中添加
#配置mongoDB地址
spring:
data:
mongodb:
#mongodb://192.168.140.100:27017/数据名.集合名
uri: mongodb://192.168.140.100:27017/why_datebase.test
@Autowired
private MongoTemplate mongoTemplate;
@Test
void testInsert() {
User user = new User();
user.setName("陈三");
user.setAge(25);
//向User表中插入数据
User user1 = mongoTemplate.insert(user);
}
@Test
void testFind(){
List<User> all = mongoTemplate.findAll(User.class);
for (User user : all) {
System.err.println(user);
}
}
@Test
void testFindById(){
//根据id查询
User user = mongoTemplate.findById("625c06dae63b0056f5f21fc8", User.class);
System.err.println(user);
}
@Test
void findUserListAnd(){
Query query = new Query(Criteria.where("name").is("张三").and("age").is(25));
//条件查询 where name = '张三' and age = 25
List<User> users = mongoTemplate.find(query, User.class);
System.err.println(users);
}
@Test
void findUserListOr(){
//条件查询:where name = '张三' or id = ‘625c066b8d584444626116ae’
Criteria name = Criteria.where("name").is("张三");
Criteria id = Criteria.where("id").is("625c066b8d584444626116ae");
Criteria criteria = new Criteria();
//合并or的查询条件
criteria.orOperator(name,id);
Query query = new Query();
query.addCriteria(criteria);
List<User> users = mongoTemplate.find(query, User.class);
System.err.println(users);
}
@Test
void testLike(){
String name = "三";
String regex = String.format("%s%s%s","^.*",name,".*$");
//Pattern.CASE_INSENSITIVE : 忽略大小写
Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
Query query = new Query(Criteria.where("name").regex(pattern));
//这样写也可以
//Query query = new Query(Criteria.where("name").regex("三"));
//模糊查询 where name like '三'
List<User> users = mongoTemplate.find(query, User.class);
for (User user : users) {
System.err.println(user);
}
}
@Test
void findPage(){
//分页查询
Integer pageNo = 1;
Integer pageSize = 2;
Query query = new Query(Criteria.where("age").is(25));
//查询记录数
long count = mongoTemplate.count(query, User.class);
System.err.println("表中记录数量为:"+count);
//分页 skip:指定起始页,limit:指定每页记录数
query.skip((pageNo-1)*pageSize).limit(pageSize);
List<User> users = mongoTemplate.find(query, User.class);
for (User user : users) {
System.err.println(user);
}
}
@Test
void testUpdate(){
//根据id查询记录
User user = mongoTemplate.findById("625cfda8fe25dc25be4edd26", User.class);
//设置要修改的值
user.setName("裂空座");
user.setAge(30);
user.setEmail("246786324@qq.com");
//修改
Query query = new Query(Criteria.where("id").is(user.getId()));
Update update = new Update();
update.set("name",user.getName());
update.set("age",user.getAge());
update.set("email",user.getEmail());
UpdateResult upsert = mongoTemplate.upsert(query, update, User.class);
long matchedCount = upsert.getMatchedCount();
System.err.println("影响行数:"+matchedCount);
}
@Test
void testRemove(){
Query query = new Query(Criteria.where("id").is("625cf65138b887613da7d143"));
DeleteResult remove = mongoTemplate.remove(query, User.class);
long deletedCount = remove.getDeletedCount();
System.err.println("删除记录数量:"+deletedCount);
}
@Autowired
private UserRepository userRepository;
@Test
void testInsert() {
User user = new User();
user.setName("水箭龟");
user.setAge(12);
User save = userRepository.save(user);
System.err.println(save);
}
@Test
void testFind(){
//查询User表中所有数据
List<User> users = userRepository.findAll();
for (User user : users) {
System.err.println(user);
}
}
@Test
void testFindById(){
//根据id查询
User user = userRepository.findById("625cf664e8279d312cf32095").get();
System.err.println(user);
}
@Test
void findUserListAnd(){
//条件查询 where name = '喷火龙' and age = 11
User user = new User();
user.setName("喷火龙");
user.setAge(11);
Example<User> example = Example.of(user);
List<User> users = userRepository.findAll(example);
for (User user1 : users) {
System.err.println(user1);
}
}
@Test
void testLike(){
//模糊查询 where email like '126'
//设置模糊查询的匹配规则
ExampleMatcher matcher = ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //containing包含
.withIgnoreCase(true);//忽略大小写
User user = new User();
user.setEmail("126");
Example<User> example = Example.of(user,matcher);
List<User> users = userRepository.findAll(example);
for (User user1 : users) {
System.err.println(user1);
}
}
@Test
void findPage(){
//分页查询
//page:0表示第一页,1表示第二也......
Pageable pageable = PageRequest.of(1, 3);
Page<User> page = userRepository.findAll(pageable);
int totalPages = page.getTotalPages();
List<User> users = page.getContent();
long totalElements = page.getTotalElements();
System.err.println("总页数:"+totalPages);
System.err.println(users);
System.err.println("总记录条数:"+totalElements);
}
@Test
void testUpdate(){
//根据id查询记录
User user = userRepository.findById("625cf664e8279d312cf32095").get();
user.setAge(20);
user.setEmail("8888888@qq.com");
//修改
//save(): 如果id值存在就修改,如果id值不存在就添加
User save = userRepository.save(user);
System.err.println(save);
}
@Test
void testRemove(){
userRepository.deleteById("625cf77371fb253316589586");
//userRepository.deleteAll(); 删除所有
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/m0_60117382/article/details/124411999
内容来源于网络,如有侵权,请联系作者删除!