java连接远程带有密码的mongodb数据库

2013-07-30 12:54 来源:www.chinab4c.com 作者:ecshop专家

?? java连接远程带有密码的mongodb数据库,这个是我们研究java以及mongodb数据库的人都必须研究的,mongo我们可以在远程设置远程的mongodb服务器。这个时候,客户端连mongo服务器,就必须通过帐户密码远程连接。也必须给mongodb设置帐户和密码

?? java连接mongodb数据库首先要连admin数据库,验证权限,选择服务器的IP以及端口才行。

?? ??? Mongo mg = new Mongo("127.0.0.1",27017);
???????? ??? DB db = mg.getDB("admin");
??? ??? ??? boolean ok = db.authenticate("system","system".toCharArray());
???????? ??? //mg.auth("system","system");
??? ??????? //查询所有的Database
??? ??????? for (String name : mg.getDatabaseNames()) {
??? ??????????? //System.out.println("dbName: " + name);
??? ??????? }

??? ???????? db = mg.getDB("test");
??? ??????? //查询所有的聚集集合
??? ??????? for (String name : db.getCollectionNames()) {
??? ??????????? //System.out.println("collectionName: " + name);
??? ??????? }

??? ??????? DBCollection goods = db.getCollection("goods");

??? ??????? //查询所有的数据
??? ??????? DBCursor cur = goods.find();
??? ??????? System.out.println(cur.count());
??? ??????? while (cur.hasNext()) {
??? ??????????? System.out.println(cur.next());
??? ??????? }
??? ??????? System.out.println(cur.count());
??? ??????? System.out.println(cur.getCursorId());
??? ??????? System.out.println(JSON.serialize(cur));

???? 来源:http://www.chinab4c.com

?