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