How to get all users in Mongo Database
MongoDB is a scalable, high-performance, open source NoSQL database.
It offers Ad hoc queries, Indexing, Replication, Load balancing, File storage (GridFS), Aggregation,
MapReduce and Server-side JavaScript execution.
This requires the library mongo-2.8.0.jar to be present in the classpath.
The following example shows how to list all users in a given Mongo database.
package com.bethecoder.tutorials.mongodb.tests;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
public class GetUsersTest {
/**
* @param args
*/
public static void main ( String [] args ) {
try {
//Connect to mongoDB with given IP and PORT
Mongo mongo = new Mongo ( "localhost" , 27017 ) ;
//Get the database object
DB database = mongo.getDB ( "mytestdb" ) ;
//Gets a collection with a given name.
DBCollection userCollection = database.getCollection ( "system.users" ) ;
//Queries for all objects in this collection
DBCursor dbCursor = userCollection.find () ;
DBObject userRecord = null ;
while ( dbCursor.hasNext ()) {
userRecord = dbCursor.next () ;
System.out.println ( userRecord ) ;
}
} catch ( UnknownHostException e ) {
e.printStackTrace () ;
} catch ( MongoException e ) {
e.printStackTrace () ;
}
}
}
It gives the following output,
{ "_id" : { "$oid" : "503bc7c672816f08a5ecc26e"} , "user" : "user1" ,
"pwd" : "86c2563c85a9cf4d5f05d4c42674bc0d" , "readOnly" : false}
{ "_id" : { "$oid" : "503bc7c672816f08a5ecc26f"} , "user" : "user2" ,
"pwd" : "a94779325b5df23dc7146b6d29e0812e" , "readOnly" : false}
{ "_id" : { "$oid" : "503bc7c672816f08a5ecc270"} , "user" : "user3" ,
"pwd" : "b54682a7b133c4078b7073afa01ee913" , "readOnly" : false}
{ "_id" : { "$oid" : "503bc7c672816f08a5ecc271"} , "user" : "user4" ,
"pwd" : "9260e6d40933f393293f764cae00eab4" , "readOnly" : false}
{ "_id" : { "$oid" : "503bc7c672816f08a5ecc272"} , "user" : "readonlyuser1" ,
"pwd" : "1255cd2eb04d2cc8c1a4739f454c652b" , "readOnly" : true}
{ "_id" : { "$oid" : "503bc7c672816f08a5ecc273"} , "user" : "readonlyuser2" ,
"pwd" : "e37efdd90c603d6fbc8bf89e38d3c0ec" , "readOnly" : true}
{ "_id" : { "$oid" : "503bc7c672816f08a5ecc274"} , "user" : "readonlyuser3" ,
"pwd" : "3ebac9f3e2abb3037b41820bc8b3e2dd" , "readOnly" : true}
{ "_id" : { "$oid" : "503bc7c672816f08a5ecc275"} , "user" : "readonlyuser4" ,
"pwd" : "b6e658e83d2407939bbac18dcfc0abdf" , "readOnly" : true}