Java插入MongoDB无法正常工作

时间:2017-06-13 18:56:43

标签: java eclipse mongodb insert

我为他做了几个不同的教程,但每次都或多或少都没有发生。由于我遇到“ClassNotFoundException”问题,我使用了这个问题中建议的mongodb驱动程序jar文件: Stackoverflow Topic

我有一个非常简单的Java项目,其中一个类测试运行主方法连接到我的数据库“local”和几个教程的集合“Countries”,数据应该按照代码中的定义插入。但是当我在命令行或Studio 3T中检查集合时,它仍然是空的。由于之前的几次测试,有一些未使用的进口。

import org.bson.Document;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try {


        MongoClient connection = new MongoClient("localhost", 27017);
        DB db = connection.getDB("local");
        DBCollection coll = db.getCollection("Countries");


         BasicDBObject doc = new BasicDBObject("title", "MongoDB").
                 append("name","Germany" ).
                 append("population", "82 000 000");

                 coll.insert(doc);
        System.out.print("Test");
        }

        catch(Exception e) {


            System.out.print(e);
            System.out.print("Test");

        }






    }

}

输出如下:

Usage : [--bucket bucketname] action
  where  action is one of:
      list                      : lists all files in the store
      put filename              : puts the file filename into the store
      get filename1 filename2   : gets filename1 from store and sends to filename2
      md5 filename              : does an md5 hash on a file in the db (for testing)

我不明白为什么插入不起作用,另外为什么System.out.print方法没有出现。 eclipse中也取消了getDB方法,说明“Mongo类型的方法getDB(字符串)已被弃用”,我真的不明白。我希望有人能帮助我让代码正常工作。 Mongod.exe正在后台运行。

0 个答案:

没有答案