6

我想使用java在mongodb中创建集合。下面是我使用的代码。我可以连接到数据库。但是集合没有发生..请帮助我

   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

4 回答 4

11

确实你有一个编译错误。

如果不存在,您应该使用db.getCollection("college")which 创建集合。

此外,当您向其中添加内容时,该集合是延迟创建的。

你可以加:

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

然后将创建具有单个文档的集合。

于 2014-10-06T10:55:04.167 回答
3

在这里我分享工作代码

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

}

}


}
于 2015-10-30T10:12:24.827 回答
1

我只是最近需要做这件事。

这是我使用的(适用于您的问题):

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);
}
于 2014-10-28T20:00:35.177 回答
0

这是我的方式

        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));
于 2018-11-23T09:50:46.387 回答