https://github.com/mongodb/mongo-java-driver/downloads
下载那个几百K的jar包即可 我下载的是mongo-2.9.0-RC2.jar 389K
下载以后,放到java工程里引入
接之前的测试
启动mongo。
然后写一个java程序
package com.javaer.mongo;
import java.net.UnknownHostException;
import java.util.Set;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
public class SimpleConnection {
/**
* @param args
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException {
Mongo m = new Mongo();
/**
* 其他连接方式
* Mongo m = new Mongo("localhost");
* Mongo m = new Mongo("localhost",27017);
* Mongo m = new Mongo(Arrays.asList(new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
*/
DB db = m.getDB("yuexiaosheng");
//列出所有connection
Set colls = db.getCollectionNames();
for (String s : colls) {
System.out.println("connection:" + s);
}
//读取一条数据
DBCollection coll = db.getCollection("mycollection");
DBObject myDoc = coll.findOne();
System.out.println(myDoc);
/**
//插入一条数据
BasicDBObject doc = new BasicDBObject();
doc.put("title","tom is 2.8");
doc.put("online","true");
coll.insert(doc);
*/
//读取集合记录总数
System.out.println(coll.getCount());
//遍历集合记录
DBCursor cursor = coll.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
System.out.println("-----------------------------------------------------------------------");
//搜索一个记录
BasicDBObject query = new BasicDBObject();
query.put("title", "tom is 2.8");
cursor = coll.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
}
}