Creating a collection in MongoDB using Java

I want to create a collection in mongodb using java. Below is the code I worked with. I can connect to the database. But the collection does not occur. 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() ); } } } 
+5
source share
3 answers

Indeed, you have a compilation error.

You should use db.getCollection("college") , which creates a collection if it does not exist.

In addition, a collection is created lazily when you add something to it.

You can add:

school.save(new BasicDBObject("key" , "value"));

Then a collection with one document will be created.

+10
source

Here I use 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()); } } } 
+2
source

I recently needed to do this.

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
source

Source: https://habr.com/ru/post/1204093/


All Articles