Spring boot integrates Mongo to solve some common connection and permission problems. Docker compose installs Mongo

Spring boot integrates Mongo to solve some common connection and permission problems. Docker compose installs Mongo

1、 Docker compose to install Mongo

version: '3.1'

services:

  mongo:
    image: mongo
    container_name: mongo
    restart: always
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: 123456

  mongo-express:
    image: mongo-express
    container_name: mongo-express
    restart: always
    ports:
      - 8081:8081
    environment:
      ME_CONFIG_MONGODB_SERVER: mongo
      ME_CONFIG_MONGODB_ADMINUSERNAME: root
      ME_CONFIG_MONGODB_ADMINPASSWORD: 123456

2、 Spring boot integrates Mongo

Maven dependency

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

There are some points to pay attention to in the yaml configuration of springboot

1、 How to configure URI

1. Using the URI configuration method to configure password, user name, etc. will not take effect

2. If you encounter permission problems, check whether the user name and password match first. If you encounter

Command failed with error 17 (ProtocolError): ‘Attempt to switch database target during SASL authentication.

This kind of error report usually ends?Authsource = admin without

spring:
  data:
    mongodb:
      uri: mongodb://root:[email protected]:27017/demo?authSource=admin

2、 Configuration of traditional SQL

1. If you are a pure digital password, for example, the author’s password is 123456, use single or double quotation marks when configuring, otherwise you will be identified incorrectly, because the receiving password uses char array, and 123456 will obviously overflow

spring:
  data:
    mongodb:
      username: root
      password: '123456'
      host: 192.168.50.150
      port: 27017
      database: demo
      authentication-database: admin

Read More: