一:设置要链接的主机名称和端口号
MongoClient client = new MongoClient("localhost",27001);
二:确定连接数据库
DB db = client.getDB("mldn");
三:确定连接表
DBCollection col = db.getCollection("dept");
四:操作数据
4.1: 添加
for (int i = 0; i < 5; i++) {
BasicDBObject obj = new BasicDBObject();
obj.append("depton", 10+i);
obj.append("dname", "技术部" + i);
obj.append("loc", "沈阳" + 2 + i);
col.insert(obj);
}
4.2:查看全部(无条件)
DBCursor cursor = col.find().skip(0).limit(3);
while(cursor.hasNext()) {
//得到每个内容
DBObject object = cursor.next();
System.out.println("部门编号:"+object.get("depton") + " 部门名称: "+object.get("dname"));
}
4.3:筛选条件
//范围查询
cond.put("depton", new BasicDBObject("$gte",11).append("$lte", 13));
//in查询
cond.put("depton", new BasicDBObject("$in",new int[] {11,13,15}));
//模糊查询,设置过滤条件
Pattern pattern = Pattern.compile("3");
cond.put("dname", new BasicDBObje("$regex",pattern));
//条件查询
DBCursor cursor = col.find(cond);
4.4:删除
//删除
DBObject dbObjectA = new BasicDBObject();
dbObjectA.put("depton", 13);
WriteResult result = col.remove(dbObjectA);
System.out.println(result.getN());//修改了几条
4.5:修改
//修改,修改时必须跟要修改的过滤条件
//设置修还的过滤条件
DBObject dbObjectA = new BasicDBObject();
dbObjectA.put("depton", 13);
//修改内容
DBObject dbObjectB = new BasicDBObject();
dbObjectB.put("$set", new BasicDBObject("dname","修改后的部门"));
//开始修改
WriteResult result = col.update(dbObjectA, dbObjectB);
五:关闭数据库链接
client.close();