驱动包下载:https://github.com/mongodb/mongo-java-driver/downloads
我下载的是
mongo-2.8.0.jar — Version 2.8.0
打开mongo shell -- 新建数据库test --( use test)
打开eclipse新建工程,把junit,mongo-2.8.0.jar导入。
新建测试类如下:
package com.db;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.bson.types.ObjectId;
import org.junit.After;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
public class DBUtils {
private static Mongo mongo;
private static DB db;
static {
try {
mongo = new Mongo("localhost", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
db = mongo.getDB("test");
}
@After
public void output() {
// 测试完显示所有
DBCollection dbc = db.getCollection("user");
DBCursor cursor = dbc.find();
while (cursor.hasNext()) {
// cursor.next就是一行记录(一个文档)
System.out.println(cursor.next());
}
}
@Test
public void testInsert() throws Exception {
DBCollection dbc = db.getCollection("user");
DBObject object = new BasicDBObject();
object.put("username", "zdw");
object.put("password", "123");
// 一个人有一个职位
// 数据库json格式:{username:"zdw",password:"123",position:{name:"工程师"}}
BasicDBObject o = new BasicDBObject();
o.put("name", "经理");
object.put("position", o);
dbc.insert(object);
object = new BasicDBObject();
object.put("username", "zhangjun");
object.put("password", "456");
// 一个人有多个职位(一个文档里有多个文档)
// 数据库json格式:{username:"zhangjun",password:"456",position:[{name:"工程师"},{name:"设计师"}]}
List<Object> list = new ArrayList<Object>();
o = new BasicDBObject();
o.put("name", "工程师");
list.add(o);
o = new BasicDBObject();
o.put("name", "设计师");
list.add(o);
object.put("position", list);
dbc.insert(object);
}
// 删除指定
@Test
public void testRemoveOne() throws Exception {
DBCollection dbc = db.getCollection("user");
DBObject o = new BasicDBObject();
o.put("username", "zhangjun");
dbc.remove(o);
}
@Test
public void testModify() throws Exception {
DBCollection dbc = db.getCollection("user");
// 根据id修改密码,需要加$set,否则所有记录的password都会被修改,其它字段删除。
int result = dbc.update(
new BasicDBObject("_id", new ObjectId(
"4ff8eaa65dbc67340278a07c")),
new BasicDBObject("$set", new BasicDBObject("password",
"4444"))).getN();
System.out.println(result);
}
@Test
public void testRemove() throws Exception {
DBCollection dbc = db.getCollection("user");
// 删除全部
dbc.drop();
}
// 查询指定
@Test
public void testFindOne() throws Exception {
DBCollection dbc = db.getCollection("user");
DBObject o = new BasicDBObject();
o.put("username", "zdw");
DBObject obj = dbc.findOne(o);
System.out.println(obj);
}
}
这种key-value存储方式,操作很方便。
源码下载