mongodb初探-小试牛刀_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > mongodb初探-小试牛刀

mongodb初探-小试牛刀

 2011/11/7 8:02:20  lijiaqian1989  http://lijiaqian1989.iteye.com  我要评论(0)
  • 摘要:1、启动数据库服务2、下载mongodb的Java驱动,并构建到java工程中,下载地址:https://github.com/mongodb/mongo-java-driver/downloads3、编写如下代码packagecom.ljq.dao;importjava.util.Date;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importjava.util.Set;importjava.util
  • 标签:MongoDB
1、启动数据库服务
2、下载mongodb的Java驱动,并构建到java工程中,下载地址:https://github.com/mongodb/mongo-java-driver/downloads
3、编写如下代码
package com.ljq.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
/**
 * Mongodb connect & insert & query simple example
 * @author jiaqianli.cn@gmail.com
 */
public class DbTest {
	public static void main(String[] args) throws Exception{
		/*
		  The Mongo object instance actually represents a pool of connections to the database;
		  you will only need one object of class Mongo even with multiple threads.
		 */
		// Mongo mongo = new Mongo();
		Mongo mongo = new Mongo("127.0.0.1");
		
		List<String> list = mongo.getDatabaseNames();
		// 打印数据库名字
		int index = 0;
		for (String db : list) {
			System.out.println("数据库"+(++index)+":"+db);
		}
		System.out.println("=============================");
		
		DB db = mongo.getDB( "mydb1" );
		Set<String> colls = db.getCollectionNames();
		// 打印mydb1中的链接
		index = 0;
		for (String s : colls) {
		    System.out.println("连接"+(++index)+":"+s);
		}
		System.out.println("=============================");
		
		// 获取某个链接
		DBCollection collection = db.getCollection("mydb1");
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("_id", UUID.randomUUID());
		data.put("name", "lijiaqian2011");
		data.put("email", "jiaqianli.cn@gmail.com");
		data.put("address", "BeiJing China");
		data.put("company", "BeiJing Boeh Technology");
		data.put("salary", 6000f);
		data.put("addtime", new Date());
		
		BasicDBObject doc = new BasicDBObject();
		doc.putAll(data);
		
		// 插入数据
		collection.insert(doc);
		
		BasicDBObject query = new BasicDBObject();
		query.put("name", "lijiaqian2011");
		
		// 查询数据
		DBObject mydoc = collection.findOne(query);
		
		System.out.println("email:"+mydoc.get("email"));
	}
}


4、执行结果如下图:




  • 大小: 14.9 KB
  • 查看图片附件
发表评论
用户名: 匿名