1.準(zhǔn)備
???? 下載Mongo Java Driver,下載地址:https://github.com/downloads/mongodb/mongo-java-driver/mongo-2.5.3.jar
???? 如果是使用maven編譯,可在pom.xml文件中加入如下依賴
???? <dependency>
????????? <groupId>org.mongodb</groupId>
????????? <artifactId>mongo-java-driver</artifactId>
????????? <version>2.5.3</version>
???? </dependency>
2.上程序
/**
?* MongoDB學(xué)習(xí)之HelloWorld
?*
?* @author <a href="mailto:gerald.chen@qq.com">GeraldChen</a>
?* @version $Id: HelloWorldTest.java,v 1.1 2011/05/26 12:42:45 gerald.chen Exp $
?*/
public class HelloWorldTest {
????? /** 數(shù)據(jù)庫(kù)連接IP */
???? public static final String DB_HOST = "192.168.35.101";
???? /** 數(shù)據(jù)庫(kù)連接端口 */
???? public static final int DB_PORT = 27017;
???? public static void main(String[] args) throws Exception {
???????? // connect to mongoDB, ip and port number
???????? Mongo mongo = new Mongo(DB_HOST, DB_PORT);
???????? // get database from MongoDB,
???????? // if database doesn't exists, mongoDB will create it automatically
???????? DB db = mongo.getDB("test_db");
???????? // Get collection from MongoDB, database named "yourDB"
???????? // if collection doesn't exists, mongoDB will create it automatically
???????? DBCollection collection = db.getCollection("test_collection");
???????? // create a document to store key and value
???????? BasicDBObject document = new BasicDBObject();
???????? document.put("id", 1001);
???????? document.put("message", "hello world mongoDB in Java");
???????? // save it into collection named "yourCollection"
???????? collection.insert(document);
???????? // search query
???????? BasicDBObject searchQuery = new BasicDBObject();
???????? searchQuery.put("id", 1001);
???????? // query it
???????? DBCursor cursor = collection.find(searchQuery);
???????? // loop over the cursor and display the retrieved result
???????? while (cursor.hasNext()) {
????????????????? System.out.println(cursor.next());
???????? }
???????? System.out.println("Done");
???}
}
2.程序輸出
關(guān)鍵詞:HelloWorld?? MongoDB?? NoSQL?? JAVA??? 程序?? 軟件?? 數(shù)據(jù)庫(kù)?? 程序員
?