Created
May 28, 2015 15:16
-
-
Save anonymous/40291bfd75eea9078e5f to your computer and use it in GitHub Desktop.
Create user and list all users
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.mongodb.BasicDBObject; | |
import com.mongodb.MongoClient; | |
import com.mongodb.client.MongoDatabase; | |
import org.bson.Document; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.List; | |
public class CreateUserExample { | |
public static void main(String[] args) { | |
MongoClient mongoClient = new MongoClient(); | |
// Create a new user in the admin database | |
MongoDatabase mongoDatabase = mongoClient.getDatabase("admin"); | |
String userName = "usr"; | |
Document command = new Document("createUser", userName) | |
.append("pwd", "Cip#erCloud@123") | |
.append("roles", Collections.singletonList("readWrite")); | |
mongoDatabase.runCommand(command); | |
// List all users in the admin database | |
Document response = mongoDatabase.runCommand(new Document("usersInfo", 1)); | |
List<Document> users = response.get("users", List.class); | |
for (Document user : users) { | |
System.out.println(user); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment