How to connect to MongoDB 3.0 using Spring Boot
My problem
Yesterday, I spent more than 5 hours trying to fix a compatibility issue between the latest version of spring-boot (1.2.6.RELEASE) and a mongoDb 3.0 database.
My problem was that I was using a free MongoDB-as-a-Service and they decided to upgrade from version 2.X to 3.0. As a result, my jhipster application could not connected to the database, and all that I could see in the logs were:
Caused by: com.mongodb.CommandFailureException: { “serverUsed” : “xxx” , “ok” : 0.0 , “errmsg” : “auth failed” , “code” : 18}
The solution
After a lot of reading, I finally manage to found what was the problem: “MongoDB 3.0 changed the default authentication mechanism from MONGODB-CR to SCRAM-SHA-1”.
In order to solve this problem, I followed these 3 steps:
- Update to the latest version of Spring Data Mongodb
- Add the latest version of the mongo-java-driver
- Set MongoClient specific options for setting credentials
1) Update to the latest version of Spring Data Mongodb
My problem was that the latest version of spring-boot-starter-data-mongodb(1.2.6.RELEASE) was using by default an older version of Spring Data MongoDB. In order to use the latest version of Spring Data MongoDB, the easiest way to update it is by setting the spring-data-releasetrain.version property in their Maven POMs to Fowler-SR2.
And here it is an snippet of my pom.xml:
[xml]
…
…
[/xml]
2) Add the latest version of the mongo-java-driver
Once you are using the latest version of Spring Data MongoDB, you will need to update the mongo java driver to the latest version, so I have added this bit to my pom.xml:
[xml]
…
…
[/xml]
3) Set MongoClient specific options for setting credentials
According to the Spring Data MongoDB Documentation “MongoDB Server generation 3 changed the authentication model when connecting to the DB. Therefore some of the configuration options available for authentication are no longer valid. Please use the MongoClient specific options for setting credentials via MongoCredential to provide authentication data.”
So you will need to set your credential using MongoCredential.createCredential method. Please have a look to this database configuration example:
[java]
@Configuration
@EnableMongoRepositories(“your_package_repositoy_name”)
@EnableMongoAuditing(auditorAwareRef = “springSecurityAuditorAware”)
public class DatabaseConfiguration extends AbstractMongoConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
@Value(“${spring.data.mongodb.host}”)
private String host;
@Value(“${spring.data.mongodb.port}”)
private Integer port;
@Value(“${spring.data.mongodb.username}”)
private String username;
@Value(“${spring.data.mongodb.database}”)
private String database;
@Value(“${spring.data.mongodb.password}”)
private String password;
@Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
@Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
@Override
public String getDatabaseName() {
return database;
}
@Override
@Bean
public Mongo mongo() throws Exception {
return new MongoClient(singletonList(new ServerAddress(host, port)),
singletonList(MongoCredential.createCredential(username,database, password.toCharArray())));
}
}
[/java]
I hope this post help you solve your problem and you don’t waste as much time as I did. Please any comments or queries let me know.
Thanks for this.
I had the same error with a Spring Boot app using a new Mongo 3.0 database. By upgrading to the latest version of the Java Mongo driver (3.0.4) and then adding the authentication mechanism param to the URI in my application.properties, I was able to get it working:
spring.data.mongodb.uri=mongodb://myusername:mypassword@localhost/?authSource=admin&authMechanism=SCRAM-SHA-1
spring.data.mongodb.database=test
Thanks!
Rich
Amazing . ! Just what i wanted
i got error when upgrading to the latest version of the Java Mongo driver (3.0.4) .
the error is : nested exception is java.lang.NoSuchMethodError: com.mongodb.DB.authenticate.
The deprecated DB.authenticate method was removed in MongoDB 3.0, are you using the method at any point in your code?
This is working. Thank you very much
Cool that worked really well.
But I had to remove @EnableMongoAuditing(auditorAwareRef = “springSecurityAuditorAware”), as it caused errors.
Thanks a lot for this post! It made my day.
Thanks for help !
Thank so much man!!!! Finally I got it…you save my life…
I share you my solution…
List servers=new ArrayList();
servers.add(new ServerAddress(“xxxxxxxxx”, portnumber));
List creds=new ArrayList();
creds.add(MongoCredential.createCredential(“yyy,”databaseName”, “XXXXXXX”.toCharArray()));
return new MongoClient(servers,
creds);
really good post man
It works fine on springBoot 1.3.2 ! Thanks
Thanks a lot!
Ignacio, thank you for this post!
Thanks so much..
Here is my updated solution:
@Bean
@Override
public MongoClient mongoClient() {
return new MongoClient(
singletonList(new ServerAddress(host, port)),
MongoCredential.createCredential(username, database, password.toCharArray()),
MongoClientOptions.builder().applicationName(appName).build());
}
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.info/register?ref=JW3W4Y3A
Hi there,
Here is the GOAT Video generator for eCommerce websites like ignaciosuay.com.
If you’re preparing for the Black Friday rush, Letstok can help you create more ads in less time.
Our AI turns your Shopify or Amazon product pages into UGC-style videos automatically — no editing, no production costs.
Store owners use it to launch campaigns faster, for a fraction of the price.
Try it free and enjoy 50% off for Black Friday:
https://www.letstok.com/
Best,
Melanie Nilsen
Letstock AI
Thanks for sharing. I read many of your blog posts, cool, your blog is very good. https://accounts.binance.com/id/register-person?ref=UM6SMJM3
Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://accounts.binance.info/ph/register-person?ref=IU36GZC4
Hi, Are you in need of a personal assistant to streamline your daily business operations and simplify your life? I’m Zain Murt, and I can assist with administrative tasks, marketing, email management, website management, data list building, AI related work, social media, content creation, project planning, bookkeeping, software training, and back-office support.
If you’re interested, please send an email to projectsexpert222@outlook.com with the tasks you need help with, and I’ll handle the rest.
Your article helped me a lot, is there any more related content? Thanks!
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good. https://accounts.binance.com/register/person?ref=W49FLGDN
Hello, Are you looking for a reliable Virtual Assistant to support your business remotely?
We provide dedicated virtual employees who can help with tasks such as data entry, lead generation, internet research, ecommerce product uploads, spreadsheet updates, website edits, and content updates.
You can hire on a monthly basis:
> Part-Time: $1200/month (80 hours)
> Full-Time: $2000/month (160 hours)
If you are interested, please reply to this email or contact us at Hireonline4455@outlook.com
Hi, I’m Mandy, a content and copywriter with over 12 years of experience creating content for various industries. I write blogs, rewrite old content, news articles, SEO-friendly web content, product descriptions, business service descriptions, newsletters, brochures, and more. My focus is on delivering content that connects with your audience, improves SEO, and gets results—all written without AI. I also provide reports from paid tools to back up my work. My rate is $50 per 1,000 words, offering great value for high-quality content.
If you’d like to improve your content, feel free to email me at creativeteamhire@outlook.com
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://accounts.binance.bh/register/person?ref=IHJUI7TF
Are you looking for a personal assistant who can handle your daily business operations and make your life easier? I can help with tasks related to admin, marketing, gathering data from multiple websites, answering emails, website management, social media, content writing, planning new projects, bookkeeping, entering data into softwares, and back-office assistance. I have an Inhouse Content writer, social media specialist, Data Entry Operator, Website Developer and Bookkeeper. My costing varies from $8/hr to $30/hr depending on type of project and its complexity.
If you are interested, send me an email at Businessgrowtogether@outlook.com with a list of tasks you want to accomplish, and We can discuss our collaboration over a video call as per your convenience.
Are you looking to enhance your brand’s social media presence with engaging and consistent content? As a social media specialist, I offer custom posts for platforms like Facebook, Instagram, and LinkedIn, designed to boost engagement and connect with your target audience. At an affordable cost of just $20 per post, you’ll receive unique and branded posts.
Contact me at socialmedia1145@outlook.com to discuss how I can help elevate your online presence!
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://www.binance.bh/register?ref=IXBIAFVY
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Hey, This is Vicky. I am a Website developer and designer specializing in WordPress, html, php, css ,js, Informative websites,E-Commerce stores. If you need any assistance in creating a new page, new design, developing new functionality, changing any existing functionality, monthly maintenance, any theme related work or uploading content, then let’s have a video call. I will show you the websites that I have developed. The best part is that I charge just $20/hr to $40/hr depending on the complexity of work.
Feel free to send me an email at hireresource009@outlook.com to discuss it further.
Hey,
We came across your store and thought it looks great.
LetsTok AI helps you create product ads and visuals without shooting or production. It also studies competitor ads and generates similar creatives tailored to your store.
If you’d like to explore it, you can start here:
https://letstokvideo.com
Cheers,
Earlene Elam
Letstok AI
Whenever you prefer not to get future messages from me, feel free to fill the form at bit. ly/fillunsubform with your domain address (URL).
Aspernstrasse 38, Montezuma, CA, USA, 91500
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Jilietwin, man, that place is blowing up. The bonuses are sweet and there are a ton of games to choose from from Jili. Worth a shot if you’re looking for something new. See for yourself! jilietwin