1.pom.xml
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.7.RELEASE</version> </parent> <groupId>com.lzufe</groupId> <artifactId>springboot-mongoDB</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.project.lombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version> </dependency> </dependencies>
2.application.yml
spring: application: name: mnongodb data: mongodb: uri: mongodb://127.0.0.1:27017/testdb
3. PersonDao
import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import org.springframework.beans.factory.annotation.Autowired; 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 java.util.List; @Component public class PersonDao { @Autowired private MongoTemplate mongoTemplate; public void savePerson(Person person){ mongoTemplate.save(person); } public List<Person> queryPersonListByName(String name){ Query query=new Query(Criteria.where("name").is(name)); return mongoTemplate.find(query,Person.class); } public List<Person> queryPersonListByName(Integer page, Integer rows) { Query query = new Query().limit(rows).skip((page - 1) * rows); return this.mongoTemplate.find(query, Person.class); } public UpdateResult update(Person person) { Query query = Query.query(Criteria.where("name").is(person.getName())); Update update = Update.update("age", person.getAge()); return this.mongoTemplate.updateFirst(query, update, Person.class); } public DeleteResult deleteById(String name) { Query query = Query.query(Criteria.where("name").is(name)); return this.mongoTemplate.remove(query, Person.class); } }