MongoDB application practice

MongoDB application practice

Applicable scenarios of MongoDB

  • Website data: Mongo is very suitable for real-time insertion, update and query, and has the replication and high scalability required for website real-time data storage
  • Cache: due to its high performance, Mongo is also suitable as the cache layer of information infrastructure. After the system restarts, the persistent cache layer built by Mongo can avoid the data source overload of the lower layer
  • Large size and low value data: using traditional relational databases to store some large-size and low value data will be more wasteful.
  • High scalability scenario: MongoDB is very suitable for databases composed of dozens or hundreds of servers. Mongo's Roadmap has included built-in support of MapReduce engine and cluster high availability solutions
  • For storage of objects and JSON data: Mongo's BSON data format is also very suitable for storage and query of documented format

Industry scenario of MongoDB

  • Game scene: use MongoDB to store game user information, user equipment, points, etc. directly in the form of embedded documents for convenient query and update.
  • Logistics scenario: use MongoDB to store the order information, and the order status will be constantly updated during the delivery process. It is stored in the form of MongoDB embedded array, and all changes of the order can be read out in one query
  • Social scene: use MongoDB to store user information and the information of friends published by users, and realize the functions of nearby people and places through geographical location index
  • IOT scenario: use MongoDB to store the information of all connected smart devices and the log information reported by the devices, and conduct multi-dimensional analysis of these information
  • Live broadcast scenario: use MongoDB to store user information, gift information, etc

You can also judge whether MongoDB can be used according to the following table:

Application characteristics Yes/No
Applications do not need transaction and complex join support
For new applications, the requirements will change, and the data model cannot be determined. I want to develop iteratively quickly
Applications need TB or even PB level data storage
The application is developing rapidly and needs to be able to expand rapidly
The application requires that the stored data is not lost
Applications need 99.999% high availability
Applications require a large number of geographical location queries and text queries

If the above conditions are met, MongoDB can be used.

MongoDB Java client

Next, we will introduce three ways to connect MongoDB. They are: MogoClient, MongoTemplate, and MongoRepository.

1. MongoClient

Introduce dependency

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.10.1</version>
</dependency>

Document addition

public static void add(){
        MongoClient mongoClient=new MongoClient("192.168.56.115",27017);
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("user");
        Document document=Document.parse("{name:'lisi',city:'bj',birth_day:new ISODate('2001-08-01'),expectSalary:18000}");
        collection.insertOne(document);
        mongoClient.close();
    }

Document query

public static void query(){
        MongoClient mongoClient=new MongoClient("192.168.56.115",27017);
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("user");
        Document sortDocument=new Document();
        sortDocument.append("expectSalary",1);
        FindIterable<Document> documents = collection.find().sort(sortDocument);
        for (Document document:documents){
            System.out.println(document);
        }
        mongoClient.close();
    }

    public static void query2(){
        MongoClient mongoClient=new MongoClient("192.168.56.115",27017);
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("user");
        FindIterable<Document> documents = collection.find(Filters.gt("expectSalary", 21000));
        for (Document document:documents){
            System.out.println(document);
        }
        mongoClient.close();
    }

2. MongoTemplate

2.1 the configuration in Spring application is as follows:

Import dependency:

<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-mongodb</artifactId>
  <version>2.0.9.RELEASE</version>
</dependency>

Inject spring beans

<!-- structure MongoDb Factory object -->
  <mongo:db-factory id="mongoDbFactory"
    client-uri="mongodb://192.168.211.133:37017/lg_resume">
  </mongo:db-factory>
  <!-- structure MongoTemplate Object of type -->
  <bean id="mongoTemplate"
class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg index="0" ref="mongoDbFactory"></constructor-arg>
  </bean>

2.2 the configuration in spring boot is as follows:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
        <version>2.2.2.RELEASE</version>
</dependency>

Profile:

spring.data.mongodb.host=192.168.56.115
spring.data.mongodb.port=27017
spring.data.mongodb.database=test

Start using mongoTemplate

@Repository
public class UserDaoImpl implements UserDao{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public  List<User> getUser(String name) {
        Query query=new Query();
        query.addCriteria(Criteria.where("name").is(name));
        List<User> users = mongoTemplate.find(query, User.class, "user");
        return users;
    }

    @Override
    public User addUser(User user) {
        User result = mongoTemplate.insert(user);
        return result;
    }

    @Override
    public List<User> getUser(String name, Double expectSalary) {
        Query query=new Query();
        query.addCriteria(Criteria.where("name").is(name).andOperator(Criteria.where("expectSalary").gt(expectSalary)));
        return mongoTemplate.find(query,User.class);
    }

    @Override
    public void updateUser(String name, Double expectSalary) {
        Query query=new Query();
        query.addCriteria(Criteria.where("name").is(name));
        Update update=new Update();
        update.set("expectSalary",expectSalary);
        mongoTemplate.updateFirst(query,update,User.class);
    }

    @Override
    public void deleteUser(String name) {
        mongoTemplate.remove(Query.query(Criteria.where("name").is(name)),User.class);
    }
}

3. MongoRepository

3.1 import dependency

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
        <version>2.2.2.RELEASE</version>
</dependency>

3.2 configuration file:

spring.data.mongodb.host=192.168.56.115
spring.data.mongodb.port=27017
spring.data.mongodb.database=test

3.3 write entity classes and add @Document("collection name")

3.4 write the Repository interface and inherit MongoRepository

public interface UserRepository extends MongoRepository<User, String> {

    List<User> findByName(String username);

    List<User> findByNameAndExpectSalaryGreaterThan(String username, Double expectSalary);

    void deleteByName(String username);
}

3.5 using Repository

@Repository
public class UserDaoImpl2 implements UserDao{


    @Autowired
    private UserRepository userRepository;

    @Override
    public  List<User> getUser(String name) {
        List<User> users = userRepository.findByName(name);
        return users;
    }

    @Override
    public User addUser(User user) {
        User result = userRepository.save(user);
        return result;
    }

    @Override
    public List<User> getUser(String name, Double expectSalary) {
        List<User> users = userRepository.findByNameAndExpectSalaryGreaterThan(name, expectSalary);
        return users;
    }

    @Override
    public void updateUser(String name, Double expectSalary) {
        User user=new User();
        user.setName(name);
        user.setExpectSalary(expectSalary);
        userRepository.save(user);
    }

    @Override
    public void deleteUser(String name) {
       userRepository.deleteByName(name);
    }
}

Posted by Incubus on Sun, 17 Jul 2022 10:35:42 +0930