2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超6個贊
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// 實(shí)例化Mongo對象,連接27017端口
Mongo mongo = new Mongo("localhost", 27017);
// 連接名為yourdb的數(shù)據(jù)庫,假如數(shù)據(jù)庫不存在的話,mongodb會自動建立
DB db = mongo.getDB("test");
// Get collection from MongoDB, database named "yourDB"
// 從Mongodb中獲得名為yourColleection的數(shù)據(jù)集合,如果該數(shù)據(jù)集合不存在,Mongodb會為其新建立
DBCollection collection = db.getCollection("test1");
// 使用BasicDBObject對象創(chuàng)建一個mongodb的document,并給予賦值。
BasicDBObject document = new BasicDBObject();
//document.put("id", 1001);
//document.put("msg", "hello world mongoDB in Java");
// 將新建立的document保存到collection中去
//collection.insert(document);
// 創(chuàng)建要查詢的document

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個贊
public class MongoDBJDBC {
public static void main(String[] args) {
try {
// 實(shí)例化Mongo對象,連接27017端口
Mongo mongo = new Mongo("localhost", 27017);
// 連接名為yourdb的數(shù)據(jù)庫,假如數(shù)據(jù)庫不存在的話,mongodb會自動建立
DB db = mongo.getDB("test");
// Get collection from MongoDB, database named "yourDB"
// 從Mongodb中獲得名為yourColleection的數(shù)據(jù)集合,如果該數(shù)據(jù)集合不存在,Mongodb會為其新建立
DBCollection collection = db.getCollection("test1");
// 使用BasicDBObject對象創(chuàng)建一個mongodb的document,并給予賦值。
BasicDBObject document = new BasicDBObject();
//document.put("id", 1001);
//document.put("msg", "hello world mongoDB in Java");
// 將新建立的document保存到collection中去
//collection.insert(document);
// 創(chuàng)建要查詢的document
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "chen");
// 使用collection的find方法查找document
DBCursor cursor = collection.find(searchQuery);
// 循環(huán)輸出結(jié)果
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println("Hello World");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
添加回答
舉報