i want to create collection in mongodb using java.The below is the code i worked with.I can connect to database.But Collection is not happening..please help me
import com.mongodb.MongoClient;
import com.mongodb.DB;
import com.mongodb.DBCollection;
public class CreateCollection{
public static void main( String args[] ){
try{
// To connect to mongodb server
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Now connect to your databases
DB db = mongoClient.getDB( "cms" );
System.out.println("Connect to database successfully");
DBCollection school = db.createCollection("college");
System.out.println("Collection mycol created successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
MongoDB creates collections automatically when you insert some documents. For example: Insert a document named seomount into a collection named SSSIT. The operation will create the collection if the collection does not currently exist. If you want to see the inserted document, use the find() command.
Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB CLIENT and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up MongoDB CLIENT. You need to download the jar mongodb-driver-3.11.
MongoDB db. createCollection(name, options) is used to create collection.
MongoClient is the interface between our java program and MongoDB server. MongoClient is used to create connection, connect to database, retrieve collection names and create/read/update/delete database, collections, document etc.
Indeed you have a compilation error.
You should use db.getCollection("college")
which creates the collection if not exist.
Also, the collection is lazily created when you add something to it.
You can add:
school.save(new BasicDBObject("key" , "value"));
The collection with a single document will be created then.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With