try {
// 实例化 Mongo 对象,连接 27017 端口
Mongo mongo = new Mongo("localhost", 27017);
// 连接名为 yourdb 的数据库,假如数据库不存在的话,mongodb 会自动建立
DB db = mongo.getDB("test");
// Get collection from MongoDB, database named "yourDB"
// 从 Mongodb 中获得名为 yourColleection 的数据集合,如果该数据集合不存在,Mongodb 会为其新建立
DBCollection collection = db.getCollection("test1");
// 使用 BasicDBObject 对象创建一个 mongodb 的 document, 并给予赋值。
BasicDBObject document = new BasicDBObject();
//document.put("id", 1001);
//document.put("msg", "hello world mongoDB in Java");
// 将新建立的 document 保存到 collection 中去
//collection.insert(document);
// 创建要查询的 document
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "chen");
// 使用 collection 的 find 方法查找 document
DBCursor cursor =collection.find(searchQuery);
// 循环输出结果
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println("Hello World");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
来源: http://www.bubuko.com/infodetail-2440312.html