MongoDB学习笔记【4】-- MongoDB Java驱动使用

官方手册:http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver

 

下载:

[root@slayer mongo]# wget https://github.com/downloads/mongodb/mongo-java-driver/mongo-2.10.1.jar

导入jar路径:

[root@slayer mongodb]# pwd
/root/demos/java/mongodb
[root@slayer mongodb]# export CLASSPATH=/root/demos/java/mongodb/mongo-2.10.1.jar:${CLASSPATH}

test.java

import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;

import java.util.Arrays;
import java.util.Set;
import java.util.Iterator;

public class test {
   public static void main(String[] args) {
      try {
         // connection
         MongoClient mongoClient = new MongoClient( "localhost" );
         DB db = mongoClient.getDB( "mydb" );

         // read collectionNames
         System.out.println("CollectionNames:");
         Set<String> colls = db.getCollectionNames();
         for (String s : colls) {
            System.out.println("\t" + s);
         }
         Iterator<String> it = colls.iterator();
         String collName = it.next();

         // select a collection to use
         DBCollection coll = db.getCollection(collName);
         // set write concern
         mongoClient.setWriteConcern(WriteConcern.JOURNALED);
         // insert a document
         BasicDBObject doc = new BasicDBObject("name", "MongoDB").
                                       append("type", "database").
                                       append("count", 1).
                                       append("info", new BasicDBObject("x", 203).append("y", 102));
         coll.insert(doc);

         // find document
         DBObject myDoc = coll.findOne();
         System.out.println("\nnew inserted document:\n" + myDoc);
      } catch ( Exception ext) {
         System.out.println("exception");
      }
   }
};

编译运行:

[root@slayer mongodb]# javac test.java
[root@slayer mongodb]# java test
CollectionNames:
        fc
        people
        system.indexes

new inserted document:
{ "_id" : { "$oid" : "50cd3bede4b0f248ede01130"} , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}

 

MongoDB学习笔记【1】-- 安装启动

MongoDB学习笔记【2】-- 试用

MongoDB学习笔记【3】-- MongoDB C驱动使用

MongoDB学习笔记【4】-- MongoDB Java驱动使用

posted @ 2013-03-04 10:54  Leo Forest  阅读(632)  评论(0编辑  收藏  举报