将文档插入mongodb数据库

时间:2018-12-04 13:21:48

标签: java mongodb

import com.mongodb.client.MongoCollection; 
import com.mongodb.client.MongoDatabase;

import java.net.UnknownHostException;

import org.bson.Document;

import com.mongodb.DB;
import com.mongodb.MongoClient; 
import com.mongodb.MongoCredential;  

public class InsertingDocument { 

   public static void main( String args[] ) {  

      // Creating a Mongo client 
      MongoClient mongo = null;
    try {
        mongo = new MongoClient( "localhost" , 27018 );
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

      // Creating Credentials 
      MongoCredential credential; 
      credential = MongoCredential.createMongoCRCredential("sampleUser", "myDb", 
                 "password".toCharArray()); 
      System.out.println("Connected to the database successfully");  

      // Accessing the database 
      DB database = mongo.getDB("myDb");

      // Retrieving a collection
      MongoCollection<Document> collection =  database.getCollection("myDb") ;//Getting error at here
      System.out.println("Collection sampleCollection selected successfully");

      Document document = new Document("title", "MongoDB") 
      .append("id", 1)
      .append("description", "database") 
      .append("likes", 100) 
      .append("url", "http://www.tutorialspoint.com/mongodb/") 
      .append("by", "tutorials point");  
      collection.insertOne(document); 
      System.out.println("Document inserted successfully");     
   } 
}

我收到类似的错误 线程“主”中的异常java.lang.ClassCastException:com.mongodb.DBApiLayer $ MyCollection无法转换为com.mongodb.client.MongoCollection     在InsertingDocument.main(InsertingDocument.java:35) 谁能解决我的问题

0 个答案:

没有答案