Reputation: 755
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.
Upvotes: 0
Views: 2357
Reputation: 11
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);
Upvotes: 1
Reputation: 42585
All Mongo user accounts are listed in the collection system.users
in 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);
}
Upvotes: 1