MongoDB set access permissions, set user, user name password access in Java

Source: Internet
Author: User
Tags auth

The following actions are based on the Windows platform

1. Start MongoDB Service

Mongod.exe--dbpath d:\mongodb-win32-x86_64-2.2.2\data--logpath d:\mongodb-win32-x86_64-2.2.2\log\mongo.log--auth

"--auth": Represents the need to access according to permissions, you must start the service with this parameter, the client can be a user name password to establish a connection

2. Start MONGO console MONGO

    1. D:\mongodb-win32-x86_64-2.2.2\bin>mongo
    2. MongoDB Shell version:2.2.2
    3. Connecting To:test
    4. >

3. Switch to the database you want to set up, create a user

    1. > Use Caotian
    2. Switched to DB Caotian
    3. > Db.adduser ("Ctadmin", "111111");
    4. {
    5. "User": "Ctadmin",
    6. "ReadOnly": false,
    7. "pwd": "790457ca1e19341d5043766e9192c5b9",
    8. "_id": ObjectId ("549943e6cbd0bdf00f57783b")
    9. }
    10. >

4. Establishing a connection in Java

    1. try {
    2. ServerAddress sa = new ServerAddress ("localhost", "27017");
    3. Mongooptions options = new Mongooptions ();
    4. Options.connectionsperhost = 200;//pool size (the drive's link pool size). /* Mongod--dbpath. \db--maxconns 20 (concurrent number) */default is 10
    5. This.mongo = new MONGO (SA, options);
    6. This.db = This.mongo.getDB ("Caotian");
    7. char[] Pwd_char = "111111". ToCharArray ();
    8. Boolean auth = db.authenticate ("Ctadmin", Pwd_char);
    9. if (!auth) {
    10. Logger.info ("======mongodb Initialization of permission validation error ======");
    11. throw new RuntimeException ();
    12. }
    13. Logger.info ("======mongodb initialization completed ======");
    14. } catch (Unknownhostexception e) {
    15. E.printstacktrace ();
    16. } catch (Mongoexception e) {
    17. E.printstacktrace ();
    18. }

MongoDB set access permissions, set user, user name password access in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.