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() );
       }
    } 
  }
4
  • Are you getting any error? Commented Oct 6, 2014 at 10:53
  • ya im getting error in the line DBCollection school = db.createCollection("college"); as required:String,DBObject but found:String Commented Oct 6, 2014 at 11:01
  • could you try DBCollection school = db.createCollection("college",null); Commented Oct 6, 2014 at 11:28
  • @KumarKailash:i tried but its showing the error like this Required : String,DBObject .. but found:String , null Commented Oct 6, 2014 at 11:32

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I dont want to insert document jus i want to create collection
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
actually my aim is to create empty collection in which i will insert document from external user entry from UI
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.
:then could me please help me with a sample for the above
|
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());
        }
    }
}

Comments

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);
}

Comments

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.