java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

java 操作 MongoDB 快速入手

https://github.com/mongodb/mongo-java-driver/downloads

下载那个几百K的jar包即可 我下载的是mongo-2.9.0-RC2.jar 389K

下载以后,放到java工程里引入
接之前的测试

启动mongo。
然后写一个java程序

package com.javaer.mongo;

import java.net.UnknownHostException;
import java.util.Set;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

public class SimpleConnection {
	
	/**
	 * @param args
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException {
		Mongo m = new Mongo();
		/**
		 * 其他连接方式
		 * Mongo m = new Mongo("localhost");
		 * Mongo m = new Mongo("localhost",27017);
		 * Mongo m = new Mongo(Arrays.asList(new ServerAddress("localhost", 27017), 
                                      new ServerAddress("localhost", 27018), 
                                      new ServerAddress("localhost", 27019)));
		 */
		DB db = m.getDB("yuexiaosheng");
		
		//列出所有connection
		Set colls = db.getCollectionNames();

		for (String s : colls) {
		    System.out.println("connection:" + s);
		}
		
		//读取一条数据
		DBCollection coll = db.getCollection("mycollection");
		DBObject myDoc = coll.findOne();
		System.out.println(myDoc);
		
		/**
		//插入一条数据
		BasicDBObject doc = new BasicDBObject();
		doc.put("title","tom is 2.8");
		doc.put("online","true");
		coll.insert(doc);
		*/
		
		//读取集合记录总数
		System.out.println(coll.getCount());
		
		//遍历集合记录
		DBCursor cursor = coll.find();
        try {
            while(cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }
        System.out.println("-----------------------------------------------------------------------");
        
        
        //搜索一个记录
        BasicDBObject query = new BasicDBObject();

        query.put("title", "tom is 2.8");
       
        cursor = coll.find(query);
        try {
            while(cursor.hasNext()) {
                System.out.println(cursor.next());
            }
        } finally {
            cursor.close();
        }
        
	}

}


This entry was posted in JAVA, 高并发与大数据 and tagged . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-mongodb/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply