java-mongodb示例

时间:2016-11-30 05:45:35

标签: java mongodb

我一直在尝试在java中执行我的第一个mongodb示例。它向我展示了错误。我已正确安装了一切。任何帮助都会被赞赏。它在线程“main”

中抛出异常异常
  

java.lang.NoSuchMethodError:   com.mongodb.ReadPreference.primary()LCOM / mongodb的/ ReadPreference;在   com.mongodb.MongoClientOptions $生成器。(MongoClientOptions.java:731)     在com.mongodb.MongoClient。(MongoClient.java:151)at   com.mongodb.MongoClient。(MongoClient.java:141)at   mongoDBExample.main(mongoDBExample.java:21)

这是我的程序代码。

   public class mongoDBExample {
    public static void main(String[] args) throws UnknownHostException {

    try {

    /**** Connect to MongoDB ****/

    MongoClient mongo = new MongoClient("localhost", 27017);

    /**** Get database ****/
    // if database doesn't exists, MongoDB will create it for you
    DB db = mongo.getDB("testdb");

    /**** Get collection / table from 'testdb' ****/
    // if collection doesn't exists, MongoDB will create it for you
    DBCollection table = db.getCollection("user");

    /**** Insert ****/
    // create a document to store key and value


    BasicDBObject document = new BasicDBObject();
    document.put("name", "mkyong");
    document.put("age", "30");
    document.put("createdDate", new Date());
    table.insert(new DBObject[] {document});


    /**** Find and display ****/
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("name", "mkyong");

    DBCursor cursor = table.find(searchQuery);

    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    /**** Update ****/
    // search document where name="mkyong" and update it with new values
    BasicDBObject query = new BasicDBObject();
    query.put("name", "mkyong");

    BasicDBObject newDocument = new BasicDBObject();
    newDocument.put("name", "mkyong-updated");

    BasicDBObject updateObj = new BasicDBObject();
    updateObj.put("$set", newDocument);

    table.update(query, updateObj);

    /**** Find and display ****/
    BasicDBObject searchQuery2
        = new BasicDBObject().append("name", "mkyong-updated");

    DBCursor cursor2 = table.find(searchQuery2);

    while (cursor2.hasNext()) {
        System.out.println(cursor2.next());
    }

    /**** Done ****/
    System.out.println("Done");

    } catch (MongoException e) {
    e.printStackTrace();
    }

  }
}

3 个答案:

答案 0 :(得分:0)

问题

MongoClient mongo = new MongoClient("localhost", 27017);

尝试使用格式

MongoClient mongo = new MongoClient(new MongoClientURI("mongodb://127.0.0.1:27017"));

答案 1 :(得分:0)

MongoClient mongo =新的MongoClient(新的MongoClientURI(“ mongodb://127.0.0.1:27017”));

是解决此问题的正确方法

答案 2 :(得分:0)

在您的代码中,以下行因其被描述而抛出异常


DB db = mongo.getDB("testdb");


将其替换为下一行,即可完成工作


MongoClient mongoClient = new MongoClient("localhost", 27017);

DB db = new DB(mongoClient, "testdb");

这应该可行;