Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Collection in MongoDB Using Java

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() );
       }
    } 
  }
like image 433
user3219005 Avatar asked Oct 06 '14 10:10

user3219005


People also ask

How do I create a collection in MongoDB?

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.

Can I use Java with MongoDB?

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.

Which command is used to create collection MongoDB?

MongoDB db. createCollection(name, options) is used to create collection.

What is MongoClient in Java?

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.


1 Answers

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.

like image 195
Ori Dar Avatar answered Oct 06 '22 07:10

Ori Dar