windows版Mongodb 安装部署
链接: 跳转
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
yml
spring:
data:
mongodb:
database: test
host: localhost
port: 27017
# username: dba
# password: dba
pojo
@Document(collection = "sms")
public class Student {
@Id
private String userid;
@Field("name")
private String name;
@Field("age")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
}
service
public interface MongoService {
void save(Student student);
}
@Service
public class MongoServiceImpl implements MongoService {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public void save(Student student) {
mongoTemplate.save(student);
}
}
controller
@RestController
public class MongoController {
@Autowired
private MongoService mongoService;
@RequestMapping("save")
public String save(@RequestParam("id")String id,@RequestParam("name")String name,@RequestParam("age")Integer age){
Student student = new Student();
student.setAge(age);
student.setName(name);
student.setUserid(id);
mongoService.save(student);
return "success";
}
}
示例
http://localhost:8080/save?id=5&name=%E5%8E%86%E5%8F%B2&age=28
用户名和密码使用说明(未配置可直连)
打开..\mongodb\bin\mongo.exe
use test
db.createUser({user:"dba",pwd:"dba",roles:["readWrite"]})
重启mongo
mongod --dbpath ..\mongodb\data\db --auth
// 再次启动项目发现连接不上mongo,加上用户名密码后可以正常使用
spring:
data:
mongodb:
database: test
host: localhost
port: 27017
username: dba
password: dba