一、准备工作
1、 首先,下载mongoDB对Java支持的驱动包
驱动包下载地址:https://github.com/mongodb/mongo-java-driver/downloadsoDB
或者 http://download.csdn.net/detail/shiyuezhong/4553453
在线查看源码:https://github.com/mongodb/mongo-java-driver
或者下载源码:http://download.csdn.net/detail/shiyuezhong/4553475
mongodb的eclipse可视化插件:http://download.csdn.net/detail/shiyuezhong/4553482
2、 下面建立一个JavaProject工程,导入下载下来的驱动包。即可在Java中使用mongoDB,
目录如下:
二、Java操作MongoDB示例
在本示例之前你需要启动mongod.exe的服务,启动后,下面的程序才能顺利执行;
1、 建立SimpleTest.java,完成简单的mongoDB数据库操作
Mongo mongo = new Mongo();// 连接本地的27017端口
// or
Mongo mongo = new Mongo( "localhost" ); // 默认端口27017
// or
Mongo mongo = new Mongo( "localhost" , 27017 ); // 指定主机与端口
连双台mongodb
//ip为主机ip地址,port为端口号,dataBaseName相当于数据库名
DBAddress left = new DBAddress("ip:port/dataBaseName");
DBAddress right = new DBAddress("ip:port/dataBaseName ");
//若一个mongodb出现问题,会自动连另外一台
Mongo mongo = new Mongo(left, right);
连多台mongodb
List<ServerAddress> mongoHostList = new ArrayList<ServerAddress>();
mongoHostList.add(new ServerAddress("ip",port));
mongoHostList.add(new ServerAddress("ip",port));
mongoHostList.add(new ServerAddress("ip",port));
Mongo mg = new Mongo(mongoHostList);
这样就创建了一个MongoDB的数据库连接对象,它默认连接到当前机器的localhost地址,端口是27017。
用户认证(可选)
在登录数据库时,在数据库启动时可以指定是否需要认证(
mongod --auth --dbpath e:\data
//前提是要把E:\mongodb\bin加到环境变量
),
此时连接时就需要用户名和密码(--serviceUser xx --servicePassword xx),如下:
boolean auth = db.authenticate(myUserName, myPassword);
DB db = mongo.getDB(“test”);
这样就获得了一个test的数据库,如果mongoDB中没有创建这个数据库也是可以正常运行的。因为mongoDB可以在没有创建这个数据库的情况下,完成数据的添加操作。当添加的时候,没有这个库,mongoDB会自动创建当前数据库。
注意:mongodb区分大小写,程序中一定要注意
得到了db,下一步我们要获取一个“聚集集合DBCollection”,通过db对象的getCollection方法来完成。
DBCollection users = db.getCollection("users");
这样就获得了一个DBCollection,它相当于我们数据库的“表”。
查询所有数据
DBCursor cur = users.find();
while (cur.hasNext()) {
System.out.println(cur.next());
}
完整代码:
package com.syz;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
public class SimpleTest {
/**
* @param args
* @throws MongoException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, MongoException {
Mongo mongo = new Mongo();
DB db = mongo.getDB("test");
DBCollection users = db.getCollection("sss");
//sss是指test数据库里面的一个集合
DBCursor cur = users.find();
while(cur.hasNext()){
System.out.println(cur.next());
}
}
}
简单例子:
public class SimpleTest {
public static void main(String[] args) throws UnknownHostException, MongoException {
Mongo mg = new Mongo();
//查询所有的Database
for (String name : mg.getDatabaseNames()) {
System.out.println("dbName: " + name);
}
DB db = mg.getDB("test");
//查询所有的聚集集合
for (String name : db.getCollectionNames()) {
System.out.println("collectionName: " + name);
}
DBCollection users = db.getCollection("sss");
//查询所有的数据
DBCursor cur = users.find();
while (cur.hasNext()) {
System.out.println(cur.next());
}
System.out.println("记录数:"+cur.count());
System.out.println("游标ID:"+cur.getCursorId());
System.out.println("JSON格式:"+JSON.serialize(cur)); }
}
2、 完成CRUD操作,首先建立一个MongoDBCRUDTest.java,基本测试代码如下:
package com.hoo.test;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.bson.types.ObjectId;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.Bytes;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.QueryOperators;
import com.mongodb.util.JSON;
public class MongoDBCRUDTest {
private Mongo mg = null;
private DB db;
private DBCollection users;
@Before
public void init() {
try {
mg = new Mongo();
//mg = new Mongo("localhost", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
//获取temp DB;如果默认没有创建,mongodb会自动创建
db = mg.getDB("temp");
//db.addUser("xiaoshi", "bar"); 在mongodb.exe窗口中新增的一个用户
if(db.authenticate("xiaoshi", "bar".toCharArray())){//如果用户名密码对的话
//获取users DBCollection;如果默认没有创建,mongodb会自动创建
users = db.getCollection("users");
//获取users DBCollection;如果默认没有创建,mongodb会自动创建
users = db.getCollection("users");
}
}
@After
public void destory() {
if (mg != null)
mg.close();
mg = null;
db = null;
users = null;
System.gc();
}
public void print(Object o) {
System.out.println(o);
}
}
3、 添加操作
在添加操作之前,我们需要写个查询方法,来查询所有的数据。代码如下:
private void queryAll() {
print("查询users的所有数据:");
//db游标
DBCursor cur = users.find();
while (cur.hasNext()) {
print(cur.next());
}
}
@Test
public void add() {
//先查询所有数据
queryAll();
print("count: " + users.count());
DBObject user = new BasicDBObject();
user.put("name", "shiyz");
user.put("age", 24);
//users.save(user)保存,getN()获取影响行数
//print(users.save(user).getN());
//扩展字段,随意添加字段,不影响现有数据
user.put("sex", "男");
print(users.save(user).getN());
//添加多条数据,传递Array对象
DBObject user1 = new BasicDBObject("name", "holy");
user1.put("name", "dddd");
user1.put("age", 24);
print(users.insert(user1, new BasicDBObject("name", "lijn")).getN());
//把user1换成user则会插入失败
// print(users.insert(user, new BasicDBObject("name", "lijn")).getN());
//添加List集合
List<DBObject> list = new ArrayList<DBObject>();
DBObject user2 = new BasicDBObject("name", "holy");
user2.put("age", 27);
list.add(user2);
DBObject user3 = new BasicDBObject("name", "jeloo");
user3.put("age", 28);
list.add(user3);
user3.put("sex", true);
list.add(user3);//user3只会插入一次
//添加List集合
print(users.insert(list).getN());
ArrayList al = new ArrayList();
DBObject tt = new BasicDBObject();
tt.put("companyID", "BJ_002");
tt.put("companyTel", "0571-88888888");
al.add(tt);
DBObject tt1 = new BasicDBObject("name", "huanglq");
tt1.put("companyID", "BJ_003");
tt1.put("companyTel", "0571-88889999");
al.add(tt1);
users.insert(al);
//查询下数据,看看是否添加成功
print("count: " + users.count());
queryAll();
}
4、 删除数据
@Test
public void remove() {
queryAll();
//id不存在也不会报错
print("删除id = 50149c799dbbbcd9be55652c:" + users.remove(new BasicDBObject("_id", new ObjectId("50149c799dbbbcd9be55652c"))).getN());
//print("删除name = dddd:" + users.remove(new BasicDBObject("name","dddd")).getN());
//print("remove age >= 24: " + users.remove(new BasicDBObject("age", new BasicDBObject("$gte", 24))).getN());
queryAll();
}
5、 修改数据
@Test
public void update() {
//print("修改:" + users.update(new BasicDBObject("_id", new ObjectId("50149eb79dbb04f61b17501d")), new BasicDBObject("age", 99)).getN());
/* print("修改:" + users.update(
new BasicDBObject("_id", new ObjectId("5014a10a5630000000003e16")),
new BasicDBObject("age", 66),
true,//如果数据库不存在,是否添加
false//false只修改第一条,true不修改
).getN()); */
/* print("修改:" + users.update(
new BasicDBObject("name", "huanglq"),
new BasicDBObject("name", "lllll"),
true,//如果数据库不存在,是否添加
false//false只修改第一条,true不修改
).getN());*/
// print(users.update(new BasicDBObject("companyID","BJ_002"),new BasicDBObject("companyID","BJ_00ww")).getN()); //多条记录也只会修改第一条
/*//整个对象重新全部修改
BasicDBObject newDocument =new BasicDBObject();//多条也是只修改第一条
newDocument.put("companyID", "BJ_00ww");
newDocument.put("type", "shared host");
newDocument.put("clients", 222);
users.update(new BasicDBObject().append("companyID", "BJ_00ww"), newDocument);
*/
/* //比如要把hosting中值为BJ_00ww的document中的type的值进行修改, //多条也是只修改第一条
BasicDBObject newDocument3 =new BasicDBObject().append("$set",
new BasicDBObject().append("name", "shiyz"));
users.update(new BasicDBObject().append("name", "buding"), newDocument3);
*/
/* //如果要更新多个document中相同的值,可以使用$multi,比如,要把所有name为shiyz的document,将它们的name的值更新为buding,
BasicDBObject updateQuery =new BasicDBObject().append("$set",
new BasicDBObject().append("name", "buding"));
users.update(new BasicDBObject().append("name", "shiyz"), updateQuery, false, true);
*/
queryAll();
}
6、 查询数据
@Test
public void query() {
//查询所有
//queryAll();
//查询id = 50149c799dbbbcd9be556530
print("find id = 50149c799dbbbcd9be556530: " + users.find(new BasicDBObject("_id",new ObjectId("50149c799dbbbcd9be556530"))).toArray());
//查询age = 24
// print("find age = 24: " + users.find(new BasicDBObject("age", 24)).toArray());
//查询age >= 24
//print("find age >= 24: " + users.find(new BasicDBObject("age", new BasicDBObject("$gte", 24))).toArray());
//查询age <= 24
// print("find age <= 24: " + users.find(new BasicDBObject("age", new BasicDBObject("$lte", 24))).toArray());
//print("查询age!=25:" + users.find(new BasicDBObject("age", new BasicDBObject("$ne", 25))).toArray());
// print("查询age in 25/26/27:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.IN, new int[] { 25, 26, 27 }))).toArray());
// print("查询age not in 25/26/27:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.NIN, new int[] { 25, 26, 27 }))).toArray());
// print("查询age exists 排序:" + users.find(new BasicDBObject("age", new BasicDBObject(QueryOperators.EXISTS, true))).toArray());
/*
print("只查询age属性:" + users.find(null, new BasicDBObject("age", true)).toArray());
print("只查属性:" + users.find(null, new BasicDBObject("age", true), 0, 2).toArray());
print("只查属性:" + users.find(null, new BasicDBObject("age", true), 0, 2, Bytes.QUERYOPTION_NOTIMEOUT).toArray());
//只查询一条数据,多条取第一条
print("findOne: " + users.findOne());
print("findOne: " + users.findOne(new BasicDBObject("age", 26)));
print("findOne: " + users.findOne(new BasicDBObject("age", 26), new BasicDBObject("name", true)));
//查询修改、删除
print("findAndRemove 查询age=25的数据,并且删除: " + users.findAndRemove(new BasicDBObject("age", 25)));
//查询age=26的数据,并且修改name的值为Abc
print("findAndModify: " + users.findAndModify(new BasicDBObject("age", 26), new BasicDBObject("name", "Abc")));
print("findAndModify: " + users.findAndModify(
new BasicDBObject("age", 28), //查询age=28的数据
new BasicDBObject("name", true), //查询name属性
new BasicDBObject("age", true), //按照age排序
false, //是否删除,true表示删除
new BasicDBObject("name", "Abc"), //修改的值,将name修改成Abc
true,
true));*/
//查询id大于等于1的记录,并且只取10条记录
DBCursor cur = users.find(new BasicDBObject("_id",new BasicDBObject("$gte",1))).limit(10);
while(cur.hasNext()){
System.out.println(cur.next());
}
//查询id大于等于1的记录,并按id进行降序 -1表示降序,1升序。
DBCursor cur = users.find(new BasicDBObject("_id",new BasicDBObject("$gte",1))).sort(new BasicDBObject("_id",-1));
while(cur.hasNext()){
System.out.println(cur.next());
}
//查询id大于等于1的记录,并跳过前10条记录显示 相当于id>10
DBCursor cur = users.find(new BasicDBObject("_id",new BasicDBObject("$gte",1))).skip(10);
while(cur.hasNext()){
System.out.println(cur.next());
}
//查询id大于等于1的记录,跳过前10条记录并且只显示10条记录。相当//于分页功能where id>10 and id<=20
DBCursor cur = users.find(new BasicDBObject("_id",new BasicDBObject("$gte",1))).skip(10).limit(10);
while(cur.hasNext()){
System.out.println(cur.next());
}
}
mongoDB不支持联合查询、子查询,这需要我们自己在程序中完成。将查询的结果集在Java查询中进行需要的过滤即可。
7、 其他操作
public void testOthers() {
DBObject user = new BasicDBObject();
user.put("name", "hoojo");
user.put("age", 24);
//JSON 对象转换
print("serialize: " + JSON.serialize(user));
//反序列化
print("parse: " + JSON.parse("{ \"name\" : \"hoojo\" , \"age\" : 24}"));
print("判断temp Collection是否存在: " + db.collectionExists("temp"));
//如果不存在就创建
if (!db.collectionExists("temp")) {
DBObject options = new BasicDBObject();
options.put("size", 20);
options.put("capped", 20);
options.put("max", 20);
print(db.createCollection("account", options));
}
//设置db为只读
db.setReadOnly(true);
//只读不能写入数据
db.getCollection("test").save(user);
}