mongoDB : java : Create a collection
Creating a collection is a three step process.
Step 1: Get Mongo client
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
Step 2: Connect to database
DB db = mongoClient.getDB("sample");
Step 3: Use the create collection method, to create collection.
DBCollection collection = db.createCollection("employee", null);
import java.net.UnknownHostException;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
public class DatabaseConnect {
/* Step 1 : get mongoCLient */
public static MongoClient getMongoClient(){
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}
return mongoClient;
}
public static void main(String args[]){
MongoClient mongoClient = getMongoClient();
/* Step 2: Connect to DB */
DB db = mongoClient.getDB("sample");
DBCollection collection = db.createCollection("employee", null);
System.out.println("Collection created ");
System.out.println("Collection employee belongs to db " + collection.getDB());
}
}
Output
Collection created
Collection employee belongs to db sample
Creating a collection is a three step process.
Step 1: Get Mongo client
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
Step 2: Connect to database
DB db = mongoClient.getDB("sample");
Step 3: Use the create collection method, to create collection.
DBCollection collection = db.createCollection("employee", null);
import java.net.UnknownHostException;
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
public class DatabaseConnect {
/* Step 1 : get mongoCLient */
public static MongoClient getMongoClient(){
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}
return mongoClient;
}
public static void main(String args[]){
MongoClient mongoClient = getMongoClient();
/* Step 2: Connect to DB */
DB db = mongoClient.getDB("sample");
DBCollection collection = db.createCollection("employee", null);
System.out.println("Collection created ");
System.out.println("Collection employee belongs to db " + collection.getDB());
}
}
Output
Collection created
Collection employee belongs to db sample
No comments:
Post a Comment