posts - 495,  comments - 11,  trackbacks - 0

1.准备

     下载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学习之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 {

      /** 数据库连接IP */
     public static final String DB_HOST = "192.168.35.101";

     /** 数据库连接端口 */
     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.程序输出


关键词:HelloWorld   MongoDB   NoSQL   JAVA    程序   软件   数据库   程序员
 

posted on 2011-05-26 20:47 jadmin 阅读(90) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: