7

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() );
       }
    } 
  }
user3219005
  • 83
  • 1
  • 2
  • 8

4 Answers4

11

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.

Ori Dar
  • 18,687
  • 5
  • 58
  • 72
  • I dont want to insert document jus i want to create collection – user3219005 Oct 06 '14 at 11:02
  • 1
    Well, as said, it's not really created if you don't put anything to it. There's no point in creating collection if you don't put anything. If you insist you can create the document, followed by a `remove` operation. Then you will see the empty collection – Ori Dar Oct 06 '14 at 11:12
  • actually my aim is to create empty collection in which i will insert document from external user entry from UI – user3219005 Oct 06 '14 at 11:34
  • 1
    So, for each insert you will call `db.getCollection("college")` anyway which will create the collection if not exist. You don't need the piece of code above for that purpose. – Ori Dar Oct 06 '14 at 11:41
  • :then could me please help me with a sample for the above – user3219005 Oct 06 '14 at 11:46
  • It seems it has already been done for you: [http://stackoverflow.com/questions/26211965/insert-document-in-mongodb-using-java](http://stackoverflow.com/questions/26211965/insert-document-in-mongodb-using-java) – Ori Dar Oct 06 '14 at 11:50
  • I can report that using `getCollection` doesn't always create the collection in the most recent MongoDB drivers when used in a replica set. – Robert Feb 06 '22 at 12:25
3

Here I am sharing the working code

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;

public class MongoDBCollection
{

    public static void main(String args[])
    {
        try
        {
            // Connect to Database
            MongoClient mongoClient=new MongoClient("localhost", 27017);
            DB db=mongoClient.getDB("analytics");
            System.out.println("Your connection to DB is ready for Use::" + db);
    
            // Create Collection
            DBCollection linked=db.createCollection("LinkedIn", new BasicDBObject()); 
            System.out.println("Collection created successfully");
        }
    
        catch(Exception e)
        {
            System.out.println(e.getClass().getName() + ":" + e.getMessage());
        }
    }
}
SQB
  • 3,926
  • 2
  • 28
  • 49
1

I just recently needed to do this very thing.

Here is what I used (adapted to your question):

String collectionName = "college");

if(!db.collectionExists(collectionName)
{
  //I can confirm that the collection is created at this point.
  DBCollection school = db.createCollection(collectionName, new BasicDBObject());      
  //I would highly recommend you check the 'school' DBCollection to confirm it was actually created
  System.out.println("Collection %s created successfully", collectionName);
}
0

Here is my way

        MongoCollection collection;
        String collectionName = "somename";
        String jsonObject = "{}";

        if (!mongoTemplate.collectionExists(collectionName)) {
            collection = mongoTemplate.createCollection(collectionName);
            logger.info("Collection %s was successfully created", collectionName);
        } else {
            collection = mongoTemplate.getCollection(collectionName);
        }

        collection.insertOne(Document.parse(jsonObject));
Stas
  • 1