Introduction to MongoDB
MongoDB is a database based on distributed file storage. Written in C + +. It aims to provide scalable high-performance data storage solutions for WEB applications.
MongoDB is a product between relational database and non relational database. It is the most functional and relational database among non relational databases. The data structure it supports is very loose. It is a json like bson format, so it can store more complex data types. Mongo's biggest feature is that the query language it supports is very powerful. Its syntax is a little similar to the object-oriented query language. It can almost realize most of the functions similar to single table query in relational database, and it also supports indexing of data.
Features: high performance, easy to deploy, easy to use, very convenient to store data.
Main functional features:
Set oriented storage, easy to store object type data
Mode freedom
Support dynamic query
Ø supports full indexing, including internal objects
Ø support replication and fault recovery
Ø use efficient binary data storage, including large objects (such as video, etc.)
Ø automatically process fragments to support the scalability of cloud computing hierarchy
Ø the file storage format is BSON (an extension of JSON)
Disadvantages: as a non relational database, MongoDB has its limitations. MongoDB does not support transaction operations, so it is recommended not to use MongoDB for applications that need transactions. In addition, MongoDB does not support join operations at present, and it is not recommended to use MongoDB for applications that need complex queries.
Does mongodb belong to memory or hard disk storage?
Mongodb's data is stored on the hard disk, but the data that needs to be read frequently will be loaded into memory, which improves the query efficiency, that is, the so-called memory data mapping, so mongodb itself eats memory. But mongodb3 It will be much better after version 0.
quick get start
pom configuration
<!-- MongoDB drive--> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.12.1</version> </dependency> <!--spring-data-mongodb--> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>2.0.2.RELEASE</version> </dependency> <!--Paging component--> <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> <version>4.0</version> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.2.0</version> </dependency>
Configure MongoDB
import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.MongoClientFactoryBean; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @EnableMongoRepositories @ComponentScan(basePackages = "com.spring.mongodb.repository") //Specifies the package for the @ Repository annotation @Configuration public class MongoDBConfig { /** * Create MongoClient * * @return * @throws Exception */ @Bean public MongoClientFactoryBean mongoClient() throws Exception { MongoClientFactoryBean mongoClientFactoryBean = new MongoClientFactoryBean(); mongoClientFactoryBean.setHost("127.0.0.1"); mongoClientFactoryBean.setPort(27017); MongoCredential credential = MongoCredential.createCredential("root", "test", "root".toCharArray()); mongoClientFactoryBean.setCredentials(new MongoCredential[]{credential}); return mongoClientFactoryBean; } /** * Configure MongoTemplate template based access * * @param mongoClient * @return */ @Bean public MongoTemplate mongoTemplate(MongoClient mongoClient) { return new MongoTemplate(mongoClient, "test"); } }
Basic operation class MongodbDao
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; 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.Repository; import com.github.pagehelper.PageInfo; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.List; /** * mongodb Basic operation class * * @param <T> * @author linhongwei */ @Repository public class MongodbDao<T extends IdEntity> { private static final Logger logger = LoggerFactory.getLogger(MongodbDao.class); private static final int DEFAULT_SKIP = 0; private static final int DEFAULT_LIMIT = 200; private Class<T> entityClass; @Autowired protected MongoTemplate mongoTemplate; public MongodbDao() { //Get the class type of the generic through the reflection mechanism Type type = this.getClass().getGenericSuperclass(); // Generic generic if(type instanceof ParameterizedType){ // Force conversion of parameterized type ParameterizedType parameterizedType = (ParameterizedType) type; // There may be more than one generic parameter in a parameterized type Type[] types = parameterizedType.getActualTypeArguments(); // Get the first element of data (User.class) entityClass = (Class<T>) types[0]; // com.oa.shore.entity.User.class } } // = = = = = = = increase = = = = = = = = = = = = = = = = = = public void save(T t) { mongoTemplate.save(t); logger.debug("save entity: {}", t); } public void insertAll(List<T> list) { mongoTemplate.insertAll(list); } // = = = = = = = delete = = = = = = = = = = = = = = = = = = = /** * delete object * * @param t */ public void delete(T t) { mongoTemplate.remove(t); } /** * Delete object by id * * @param id */ public void deleteById(String id) { Criteria criteria = Criteria.where("id").is(id); Query query = new Query(criteria); mongoTemplate.remove(query, entityClass); } /** * Delete according to condition */ public void delete(Query query) { mongoTemplate.remove(query, entityClass); } /** * Delete all data of the collection */ public void deleteAll() { mongoTemplate.dropCollection(entityClass); } // = = = = = = = change = = = = = = = = = = = = = = = = = = public void update(Query query, Update update) { mongoTemplate.findAndModify(query, update, entityClass); } // = = = = = = = search = = = = = = = = = = = = = = = = = = = public List<T> findAll() { return mongoTemplate.findAll(entityClass); } /** * Find list by query * * @param query * @return */ public List<T> find(Query query) { return mongoTemplate.find(query, entityClass); } /** * Sort by field - order < br / > * * @param query Query criteria < br / > * @param properties Sort field < br / > * @return */ public List<T> findWithOrderAsc(Query query, String... properties) { Sort sort = new Sort(Direction.ASC, properties); query.with(sort); return mongoTemplate.find(query, entityClass); } /** * Sort by field - reverse < br / > * * @param query Query criteria < br / > * @param properties Sort field < br / > * @return */ public List<T> findWithOrderDesc(Query query, String... properties) { Sort sort = new Sort(Direction.DESC, properties); query.with(sort); return mongoTemplate.find(query, entityClass); } /** * Find an object based on query * * @param query * @return */ public T findOne(Query query) { return mongoTemplate.findOne(query, entityClass); } /** * Query object by id * * @param id * @return */ public T findById(String id) { return mongoTemplate.findById(id, entityClass); } /** * Query objects by id and collection name * * @param id * @param collectionName * @return */ public T findById(String id, String collectionName) { return mongoTemplate.findById(id, entityClass, collectionName); } /** * Query paging tips: [don't skip too many pages. Skipping too many pages will seriously affect the efficiency. Don't skip up to 20000 pages] * * @param page * @param query * @return */ public PageInfo<T> findPage(PageInfo<T> page, Query query) { long count = this.count(query); page.setTotal(count); int pageNumber = page.getPageNum(); int pageSize = page.getPageSize(); query.skip((pageNumber - 1) * pageSize).limit(pageSize); List<T> list = this.find(query); page.setList(list); return page; } public long count(Query query) { return mongoTemplate.count(query, entityClass); } /** * Get the name of the collection. The default is the name of dao template T < br / > * For example: studentscoredao extensions mongodbdao < b > & lt; StudentScore></ b> <br/> * The returned name is: < b > studentscore</b> * * @return */ private String getCollectionName() { return entityClass.getSimpleName(); } }
Base entity class IdEntity
import java.io.Serializable; /** * Entity base class. All entities inherit this class * @author linhongwei */ public class IdEntity implements Serializable { private static final long serialVersionUID = -8279493522154678891L; private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } }
test
1. Entity class StudentScore
import java.io.Serializable; import java.util.List; /** * Test entity class * @author linhongwei */ public class StudentScore extends IdEntity implements Serializable { private static final long serialVersionUID = 1126745404897398026L; /** * Student name */ private String username; /** * Student achievement */ private List<Double> scoreList; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public List<Double> getScoreList() { return scoreList; } public void setScoreList(List<Double> scoreList) { this.scoreList = scoreList; } @Override public String toString() { return "StudentScore{" + "username='" + username + '\'' + ", scoreList=" + scoreList + '}'; } }
2. dao operation class of entity class StudentScoreDao
import com.spring.mongodb.MongodbDao; import com.spring.mongodb.document.StudentScore; import org.springframework.stereotype.Repository; /** * Inherit mongodbdao < br / > * This class has defined the addition, deletion, modification, query and paging methods of StudentScore < br / > * @author linhongwei */ @Repository public class StudentScoreDao extends MongodbDao<StudentScore> { }
3. Test verification
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes={RootConfig.class, WebConfig.class}) //If it is configured by Java Config, specify the relevant configuration class @WebAppConfiguration public class MongoDbTest { @Autowired private StudentScoreDao studentScoreDao; @Test public void test(){ StudentScore studentScore = new StudentScore(); studentScore.setUsername("hello"); studentScore.setId("1234567"); studentScore.setScoreList(Arrays.asList(95d, 97d, 78d)); studentScoreDao.save(studentScore); StudentScore info = studentScoreDao.findById("1234567"); System.out.println(info.toString()); } }
MongoTemplate API
Common methods:
- mongoTemplate.findAll(Student.class): query all data of Student documents
- mongoTemplate. Findbyid (< id >, Student. Class): query the data whose Student document id is id
- mongoTemplate.find(query, Student.class);: Query according to the query criteria in query
- mongoTemplate.upsert(query, update, Student.class): modify
- mongoTemplate.remove(query, Student.class): delete
- mongoTemplate.insert(student): New
Query object:
(1) Create a query object (used to encapsulate all condition objects), and then create a criteria object (used to build conditions)
(2) Accuracy conditions: criteria and(“key”). is("condition"); Fuzzy condition: criteria and(“key”). regex("condition")
(3) Encapsulation condition: query addCriteria(criteria)
(4) Greater than (create new criteria): criteria gt = criteria where(“key”). gt ("condition")
Less than (create new criteria): criteria lt = criteria where(“key”). lt ("condition")
(5)Query.addCriteria(new Criteria().andOperator(gt,lt));
(6) There can only be one andOperator() in a query. Its parameter can also be a Criteria array.
(7) Sort: query with(new Sort(Sort.Direction.ASC, "age"). and(new Sort(Sort.Direction.DESC, "date")))