0

I'm currently creating a Java application that connects with a MongoDB and performs various data base operations such as find, insert and update from the application.

I created a dialog form from were a user can add multiple users (using method addUser(String username, char[] passwd, boolean readOnly) ) with both the read and readwrite roles. I would like to be able to list all users by clicking a button from this dialog box and then right clicking on a specific user to be able to delete the users. (using method removeUser(String username)).

The problem is that after several research on the net I cannot find any library that provides such method (to return all the users) or I have no idea on how to get this result.

This is an assignment however it is not a specific question since the assignment is more related to the database operations. However I would like to add this functionality since it will be quite cool. Any help is greatly appreciated.

2 Answers 2

1

All Mongo user accounts are listed in the collection system.usersin the admin database.

See http://docs.mongodb.org/manual/reference/system-users-collection/ for the data format.

Alternatively you can use the command usersInfo:

BasicDBObject dbStats = new BasicDBObject("usersInfo", 1);
CommandResult command = db.command(dbStats);
System.out.println(command.get("users"));
BasicDBList users = (BasicDBList) command.get("users");
for (Object u : users) {
    String username = (String) ((BasicDBObject) u).get("user");
    System.out.println(username);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Robert this worked fine. Can you please explain how I am going to return only the user names instead of the entire document from the result set.
1

I've also faced this problem. Because the first answer(Robert's answer) is old, I gave my new answer;

Firstly, this is my Maven info:

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.8.0</version>
    </dependency>

Secondly, I used the runCommand of JDK, you can check the API doc as well. This is the theory link: link, the most important info: link

Finally, my code:

Document dbStats = new Document("usersInfo", 1);
Document command = db.runCommand(dbStats);
ArrayList<Document> users = (ArrayList<Document>) command.get("users");
System.out.println(users);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.