基于Docker部署MongoDB
docker run -itd --name mongo -p 27017:27017 mongo --auth
docker exec -it mongo mongo admin
# 创建一个名为 admin,密码为 123456 的用户。
> db.createUser({ user:'admin',pwd:'123456',roles:[ { role:'userAdminAnyDatabase', db: 'admin'},"readWriteAnyDatabase"]});
# 尝试使用上面创建的用户信息进行连接。
> db.auth('admin', '123456')
TIP
用NoSQLBooster for MongoDB登录MongoDB创建database,并在database内创建collection
增加Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
application.yml文件增加配置,demo
为之前创建的database的名字
spring:
data:
mongodb:
uri: mongodb://122.51.59.25:27017/demo
username: admin
先创建实体关联collection,demo_collection
为之前创建的collection的名字
package fun.gudu.modules.entity;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
@Data
@Document(collection = "demo_collection")
public class MongoEntity implements Serializable {
@Id
private Long id;
private String title;
private String description;
private String by;
private String url;
}
创建接口类
package fun.gudu.modules.mapper;
import fun.gudu.modules.entity.MongoEntity;
import java.util.List;
public interface MongoMapper {
void saveMongo(MongoEntity mongoEntity);
void removeMongo(Long id);
void updateMongo(MongoEntity mongoEntity);
MongoEntity findMongoById(Long id);
List<MongoEntity> findLikeByFiledAndValue(String filed, String... value);
}
创建MongoDB的操作方法并注入MongoTemplate
,同时实现上面的接口类
package fun.gudu.modules.service.impl;
import fun.gudu.modules.entity.MongoEntity;
import fun.gudu.modules.mapper.MongoMapper;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
@Component
public class MongoServiceImpl implements MongoMapper {
@Resource
private MongoTemplate mongoTemplate;
// 新增
@Override
public void saveMongo(MongoEntity mongoEntity) {
mongoTemplate.save(mongoEntity);
}
// 删除,两种方法都可以
@Override
public void removeMongo(Long id) {
MongoEntity mongoEntity = new MongoEntity();
mongoEntity.setId(id);
mongoTemplate.remove(mongoEntity);
// Criteria criteria = Criteria.where("id").is(id);
// Query query = new Query(criteria);
// mongoTemplate.remove(query, MongoEntity.class);
}
// 更新
@Override
public void updateMongo(MongoEntity mongoEntity) {
Query query = new Query(Criteria.where("id").is(mongoEntity.getId()));
Update update = new Update();
update.set("title", mongoEntity.getTitle());
update.set("description", mongoEntity.getDescription());
update.set("by", mongoEntity.getBy());
update.set("url", mongoEntity.getUrl());
mongoTemplate.updateFirst(query, update, MongoEntity.class);
}
// 根据id查询
@Override
public MongoEntity findMongoById(Long id) {
Query query = new Query(Criteria.where("id").is(id));
MongoEntity mongoEntity = mongoTemplate.findOne(query, MongoEntity.class);
return mongoEntity;
}
// 根据指定字段和值进行查询
@Override
public List<MongoEntity> findLikeByFiledAndValue(String filed, String... value) {
Criteria criteria = new Criteria();
List<Criteria> criteriaLists = new ArrayList<>();
for (String s : value) {
Pattern pattern = Pattern.compile("^.*" + s + ".*$", Pattern.CASE_INSENSITIVE);
criteriaLists.add(Criteria.where(filed).regex(pattern));
}
criteria.orOperator(criteriaLists.stream().toArray(Criteria[]::new));
Query query = new Query(criteria);
List<MongoEntity> all = mongoTemplate.find(query, MongoEntity.class);
return all;
}
}
进行测试
package fun.gudu;
import com.alibaba.fastjson.JSONObject;
import fun.gudu.modules.entity.MongoEntity;
import fun.gudu.modules.mapper.MongoMapper;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.xmlbeans.XmlException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ElasticSearchDemoApplication.class)
public class ElasticSearchDemoApplicationTest {
@Autowired
private MongoMapper mongoMapper;
@Test
public void saveMongoDocTest() {
StringBuilder result = new StringBuilder();
File file = new File("D:\\estest\\xxx.doc");
try {
FileInputStream fis = new FileInputStream(file);
HWPFDocument doc = new HWPFDocument(fis);
result.append(doc.getText());
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i <100; i++) {
MongoEntity mongoEntity = new MongoEntity();
mongoEntity.setId((long) i);
mongoEntity.setTitle("xxx"+i+".doc");
mongoEntity.setDescription(String.valueOf(i));
mongoEntity.setBy("gudufun");
mongoEntity.setUrl("https://gudu.fun");
mongoMapper.saveMongo(mongoEntity);
}
}
@Test
public void saveMongoTest() {
MongoEntity mongoEntity = new MongoEntity();
mongoEntity.setId(145L);
mongoEntity.setTitle("xxx.doc");
mongoEntity.setDescription("关注gudu.fun,专注于开发技术的研究与知识分享");
mongoEntity.setBy("gudufun");
mongoEntity.setUrl("https://gudu.fun");
mongoMapper.saveMongo(mongoEntity);
}
@Test
public void removeMongoTest() {
mongoMapper.removeMongo(2L);
}
@Test
public void updateMongoTest() {
MongoEntity mongoEntity = new MongoEntity();
mongoEntity.setId(1L);
mongoEntity.setTitle("xxx.doc");
mongoEntity.setDescription("关注gudu.fun,专注于开发技术的研究与知识分享");
mongoEntity.setBy("gudufun");
mongoEntity.setUrl("https://gudu.fun");
mongoMapper.updateMongo(mongoEntity);
}
@Test
public void findMongoByIdTest() {
MongoEntity mongoEntity = mongoMapper.findMongoById(965L);
System.out.println(JSONObject.toJSONString(mongoEntity));
}
@Test
public void findMongoLikeTest() {
List<MongoEntity> likeByFiledAndValue = mongoMapper.findLikeByFiledAndValue("title", "65", "43", "45");
System.out.println(JSONObject.toJSONString(likeByFiledAndValue));
}
}