how to specify database name in spring data mongoDB

28,471

Solution 1

Add to the application.properties a line

spring.data.mongodb.database=your_db_name

That worked for me, maybe too late for you but this could help someone looking for the same problem. see more properties here!

Solution 2

For Spring-Boot:

You can either rely on autoconfiguration and then type in your application.properties file:

spring.data.mongodb.database=your_db_name

or if you don't want to rely on Spring-boot autoconfiguration you can simply:

import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

/**
 * MonfoConfig
 */
@Configuration
public class MongoConfig {

    @Bean
    public MongoDbFactory mongoDbFactory() {

        MongoClient mongoClient = new MongoClient("127.0.0.1:27017");

        return new SimpleMongoDbFactory(mongoClient, "databasenamehere" );
    }

    @Bean
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoDbFactory());
    }
}

If you want to follow that path - I suggest having a look into into Spring Boot's Conditions Evaluation Report (https://www.baeldung.com/spring-boot-auto-configuration-report) and tweaking what you need to tweak. Hope this helps.

Solution 3

FWIW, I am able to change the mongo database name using the combination of Sezin Karli and Sam's code above, despite the solution not working in Sam's situation.

My POM file contains only this reference to mongodb:

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

Specifically, first I created a beans.xml file in resources with the following information:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <mongo:mongo-client credentials="user:password@database" />

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongo" ref="mongo"/>
        <constructor-arg name="databaseName" value="myDBName"/>
    </bean>
</beans>

Next, I changed my main to load the configuration via:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

Note: This must execute first in main().

Lastly, I added extends AbstractMongoConfiguration to my start-class and implemented

    @Override
    public String getDatabaseName() {
        return "myDBName";
    }

    @Override
    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient("localhost" , 27017 );
    }

The database name was specified in two locations. Unfortunately, this appears necessary for success.

Solution 4

Your configuration seems to be fine Sam. Are you sure there's a db called "MyDB"? Or are you sure that you don't also set the db name in somewhere else (such as app context xml) like below.

 <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
     <constructor-arg name="mongo" ref="mongo"/>
     <constructor-arg name="databaseName" value="demo"/>
   </bean>
Share:
28,471

Related videos on Youtube

Sami
Author by

Sami

Updated on July 09, 2022

Comments

  • Sami
    Sami almost 2 years

    I am using Mongo repositories to perform CRUD operations as in the code below. Although this code works, but the documents and collections are created in a different DB than the one that I want. How can I explicitly specify a DB name to which documents will be stored.

    The POJO class:

    @Document(collection = "actors")
    public class Actor 
    {
      @Id
      private String id;
      ...
      //constructor
      //setters & getters
    }
    

    The repository:

    public interface ActorRepository extends MongoRepository<Actor, String> 
    {
      public Actor findByFNameAndLName(String fName, String lName);
      public Actor findByFName (String fName);
      public Actor findByLName(String lName);
    }
    

    The service that uses the repository:

    @Service
    public class ActorService 
    {
      @Autowired
      private ActorRepository actorRepository;
    
      public Actor insert(Actor a)
      {
        a.setId(null);
        return actorRepository.save(a);
      }
    } 
    

    And I access the service from a REST controller class:

    @RestController
    public class Controllers 
    {
    
      private static final Logger logger = Logger.getLogger(Controllers.class);
      private static final ApplicationContext ctx = new  AnnotationConfigApplicationContext(SpringMongoConfig.class);
    
      @Autowire
      private ActorService actorService;
    
      @RequestMapping(value="/createActor", method=RequestMethod.POST)
      public @ResponseBody String createActor(@RequestParam(value = "fName") String fName,
            @RequestParam(value = "lName") String lName,
            @RequestParam(value = "role") String role)
      {
        return actorService.insert(new Actor(null,fName,lName,role)).toString();
    
      }
    
     ...
    }
    

    I have created this spring mongoDB configuration class which has the option of setting DB name, but could not figure out how to use it with the repositories above.

    @Configuration
    public class SpringMongoConfig extends AbstractMongoConfiguration
    { 
        @Bean
        public GridFsTemplate gridFsTemplate() throws Exception 
        {
            return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
        }
    
        @Override
        protected String getDatabaseName() 
        {
            return "MyDB";
        }
    
        @Override
        @Bean
        public Mongo mongo() throws Exception 
        {
            return new MongoClient("localhost" , 27017 );
        }
    
        public @Bean MongoTemplate mongoTemplate() throws Exception 
        {
            return new MongoTemplate(mongo(), getDatabaseName());
        }    
    }
    
  • Sami
    Sami over 9 years
    yes there is DB and I don't use any other configurations, however your question made me realize that it is GridFsStore so it has only two collections (chunks and files). Not sure if its possible to use it for other collections too?
  • Sami
    Sami over 9 years
    Changing the DB to another one (not GridFs) did not also work. Even if the I drop the DB, it creates a new DB called test and store the documents there.
  • Sezin Karli
    Sezin Karli over 9 years
    If youre sure that theres no test db reference in your project, maybe you can try another spring mongo config that you will find by googling. Sorry I couldnt help further
  • Witold Kaczurba
    Witold Kaczurba about 5 years
    The AbstractMongoConfiguration did not seem to work for me (spring boot)... Besides the abstract class was changed in 2017. It might be worth updating the answer to get upvotes ;-). Cheers.
  • Andrew Fielden
    Andrew Fielden over 4 years
    The link is dead.