Mongodb自己封装的工具类

如何开启链接

链接本地的monogdb数据库

MongoClient client = new MongoClient("localhost",27017);

 

获取为itcast的数据库对象

MongoDatabase db =client.getDatabase("itcast");

 

从数据库中获取为itcast的文档对象

MongoCollection<Document>collection =  db.getCollection("itcast");

 

 

Mongdb中的CURD操作

注意这些操作都是针对文档对象,就类型域mysql中的表

查询所有

获取查询的所有文档迭代对象

FindIterable<Document> it = collection.find();

 

获取所有文档对象的油标对象

      MongoCursor<Document> cursor = it.iterator();

 

    对获取的油标遍历并获取文档对象

       while(cursor.hasNext()){

          Document doc =cursor.next();

          String name=doc.getString("name");

          Double age =doc.getDouble("age");

          ObjectId id =doc.getObjectId("_id");

          System.out.println(name+":"+age+":"+id);

       }

   

   关闭资源

       cursor.close();

       client.close();

 

 

 

指定查询

这类似域 10<age<23

BasicDBObject filter =new  BasicDBObject("age",new BasicDBObject("$gt",10).append("$lt", 23));

 

这类似与and name =‘yinchong’

filter.append("name", "yinchong");

 

执行条件查询

FindIterable<Document>it = collection.find(filter);

 

遍历结果  

MongoCursor<Document>cursor = it.iterator();

 while(cursor.hasNext()){

            Document doc = cursor.next();

            String name = doc.getString("name");

            Double age = doc.getDouble("age");

            ObjectId id = doc.getObjectId("_id");

            System.out.println(name+": "+age+": "+id);

       }

 

关闭资源

cursor.close();

client.close();

 

插入数据

这句类似插入json对象为

  {

  name:’冲冲’,

   age:20,

    bobby:{

       grily:’翠翠’,

       game:’lol’,

}

解释:

 这里的插入其实利用map来实现。就好比如所你要插入的bean中含用bean是你需要再创建一个map来存放那个对象再把这个map放入到上一个map

Map<String,Object>map = new HashMap<String,Object>();

       map.put("name", "冲");

       map.put("age", 24);

       map.put("gender", "");

       Map<String,Object> hobby = newHashMap<String,Object>();

       hobby.put("grily", "翠");

       hobby.put("game", "lol");

       map.put("hobby", hobby);

 

        生成一个文档对象

       Document doc = new Document(map);

 

        插入进去

       collection.insertOne(doc);

        client.close();

 

删除数据

Bson filter =new BasicDBObject("_id",new ObjectId("584961d9fbdb38f43018ecbb"));

      

collection.deleteOne(filter);

client.close();

 

 

 

更新数据

对于更新数据推荐使用ObjectId来实现

Bson filter = new BasicDBObject("_id",new ObjectId("584961e8fbdb38f43018ecbc"));

 

把要更新的数据采用map存放然后利用构造方法生产BasicDBObject对象

Map<String,Object>map = new HashMap<String,Object>();

map.put("name", "张玉洁");

map.put("age", 20);

Bson update = newBasicDBObject(map);

 

更新的条件和更新的数据   

collect.updateOne(filter,new BasicDBObject("$set",update));

client.close();

 

总结:Monogodb最大的特点就是操作文档,它的数据变相的在使用map原因很简单它的存储是json格式的使用map可以很好的表现出来

 

几个重要的类:

Document:注意不是w3c的jar包(文档对象一起以它为中心)

BasicDBObject:常用的方法append

常用的构造方法:

 BasicDBObject(Map<String,Object>map)

 BasicDBObject(String , Object )

 

 

 

一: Insert操作

     上一篇也说过,文档是采用“K-V”格式存储的,如果大家对JSON比较熟悉的话,我相信学mongodb是手到擒来,我们知道JSON里面Value

可能是“字符串”,可能是“数组”,又有可能是内嵌的一个JSON对象,相同的方式也适合于BSON。

      常见的插入操作也就两种形式存在:“单条插入”和“批量插入”。

   

    ①  单条插入

         先前也说了,mongo命令打开的是一个javascript shell。所以js的语法在这里面都行得通,看起来是不是很牛X。     

public class MongoDBUtils {

private static MongoClient client;
private static MongoDatabase db;
private static MongoCollection<Document> collection;


// 将查询的数据设置到bean上
public static <T> List<T> data2Bean(Class<T> clazz,
MongoCursor<Document> cursor) {
try {

List<T> array = new LinkedList<T>();
while (cursor.hasNext()) {
Document doc = cursor.next();
T bean = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
if (fields != null) {
for (Field field : fields) {
field.setAccessible(true);
                        setData(bean, field, doc);
}
array.add(bean);
}


}

return array;


} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (cursor != null) {
cursor.close();
}
}
}

//传入bean返回Document进行插入
public static<T> Document transform2Doc(T bean) throws Exception{
Class clazz = bean.getClass();
HashMap<String,Object> data = new HashMap<String,Object>();
Field[] fields = clazz.getDeclaredFields();
if(fields!=null){
for(Field field:fields){
field.setAccessible(true);
String fname = field.getName();
if(fname.equals("id"))
continue;
Object value = field.get(bean);
data.put(fname, value);
}
}
return new Document(data);
}

/**
* 开启链接
* @param address
* @param port
*/
public static void openClient(String address,int port){
 if(client!=null){
 client.close();
 client = null;
 }
client = new MongoClient(address,port);
}

/**
* 打开数据库链接池
* @param dbName
*/
public static void openDatabase(String dbName){
if(client==null)
throw new RuntimeException("请先开启链接,先调用openClient");
db = client.getDatabase(dbName);
}


/**
* 开启数据库链接包括开启
* @param address
* @param port
* @param dbName
*/
public static void openAll(String address,int port,String dbName,String colName){
if(client==null)
client = new MongoClient(address,port);
if(db==null)
db = client.getDatabase(dbName);
if(collection==null)
collection = db.getCollection(colName);
}


/**
* 插入一条数据
* @param bean
*/
public static<T>  void  insertOne(T bean){
try {
collection.insertOne(transform2Doc(bean));
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 修改一条数据
* @throws IllegalAccessException 
* @throws IllegalArgumentException 
*/
public static<T> void update(Map<String,Object> condition,T bean) throws Exception{
BasicDBObject filter = new BasicDBObject();
Set<String> keys = condition.keySet();
for(String key:keys){
if(key.equals("id")){
filter.append("_id", new ObjectId(condition.get(key)+""));
continue;
}
filter.append(key, condition.get(key));
}
Map<String,Object> newData = new HashMap<String,Object>();
Class clazz = bean.getClass();
//便利获取所有的字段并将不为空的数据保存到map中
   Field[] fields = clazz.getDeclaredFields();
   for(Field field:fields){
    field.setAccessible(true);
    Object tv = field.get(bean);
    if(tv==null)
    continue;
    newData.put(field.getName(), tv);
   }

Bson update = new BasicDBObject(newData);
collection.updateMany(filter,new BasicDBObject("$set", update) );

}

/**
* 删除数据
*/
public static void delete(Map<String,Object> condition){
BasicDBObject filter = new BasicDBObject();
Set<String> keys = condition.keySet();
for(String key:keys){
if(key.equals("id")){
filter.append("_id", new ObjectId(condition.get(key)+""));
continue;
}
filter.append(key, condition.get(key));
}
collection.deleteMany(filter);
}


/**
* 查询所有数据
*/
public static<T> List<T> findAll(Class clazz){
FindIterable<Document> it = collection.find();
MongoCursor<Document> cursor = it.iterator();
return data2Bean(clazz, cursor);
}


/**
* 查询指定数据
*/
public static<T> List<T> findCondition(Map<String,Object> condition,Class clazz){
BasicDBObject filter = new BasicDBObject();
Set<String> keys = condition.keySet();
for(String key:keys){
if(key.equals("id")){
filter.append("_id", new ObjectId(condition.get(key)+""));
continue;
}
filter.append(key, condition.get(key));
}
FindIterable<Document> it = collection.find(filter);
MongoCursor<Document> cursor = it.iterator();
return data2Bean(clazz, cursor);
}

public static void  close(){
if(client!=null){
client.close();
client=null;
}
}

private static <T> void setData(T bean,Field field,Document doc) throws Exception{
String type = field.getType().getSimpleName();
String name = field.getName();
if("String".equals(type)&&"id".equals(name)){
ObjectId id = doc.getObjectId("_id");
String data = id.toString();
field.set(bean, data);
}else if("Double".equals(type)){
Double data = doc.getDouble(name);
field.set(bean, data);
}else if("String".equals(type)){
String data = doc.getString(name);
field.set(bean, data);
}else if("Date".equals(type)){
Date data = doc.getDate(name);
field.set(bean,data);
}else if("Boolean".equals(type)){
Boolean data = doc.getBoolean(name);
field.set(bean, data);
}else if("Integer".equals(type)){
String value = null;
try{
value = doc.getDouble(name)+"";
}catch(ClassCastException e){
value = doc.getInteger(name)+"";
}
int index = value.lastIndexOf(".");
if(index>-1)
value = value.substring(0,index);
Integer data = Integer.parseInt(value);
field.set(bean, data);
}else if("Long".equals(type)){
String value = null;
try{
value = doc.getDouble(name)+"";
}catch(ClassCastException e){
value = doc.getLong(name)+"";
}
int index = value.lastIndexOf(".");
if(index>-1)
value = value.substring(0,index);
Long data = Long.parseLong(value);
field.set(bean,data);
}else if("Float".equals(type)){
Float data =Float.parseFloat(doc.getDouble(name)+"");
field.set(bean, data);
}

}

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
最近重构并优化了一套后端服务的代码: 1. 设计并开发高效的C++对象池算法,时间复杂度为 O(1) 在整个重构框架中,对象池是负责管理内存的底层基本模块 2. 利用命令模式的思想开发 Redis 子模块 抽象出方便高效的接口提供给上层程序员使用 3. 利用组合模式和装饰模式的思想开发 MongoDB 数据库查询条件装饰器 将查询条件和数据库 MongodbModule 数据模型进行解耦合 4. 抽象出一套 MongoDB Module 结果集接口 通过模板和特化技术实现 string/int 等不同索引类型的结果集 5. 开发 AbstractMongodbModule 类处理通用的 MongoDB 数据库表数据操作 数据库中不同的表都有自己的 AbstractMongodbModule 子类对应 6. 用 Perl 开发自动代码生成器,上层程序员对照数据库表结构写 .tmpl 配置文件, 自动生成该数据库表的 MongodbModule 子类,减轻程序员新增表时的工作量 7. 结合 Redis 模块和 MongoDB 模块,开发 HierarchicalModule 分层数据模型 构造一个 Redis 缓存层 + MongoDB 持久层的后台 Server 架构 并通过简单方便的接口供上层程序员使用,具体的数据分层处理对上层程序员是黑盒的 8. 设计并开发整套缓存层使用的 KEY 规则,方便缓存更新 结合公司的数据订阅系统进行 Redis缓存层 + MongoDB 持久层数据更新功能 9. 重构后的分层数据架构比原有接口效率提高 5 - 400 倍(返回数据记录条数从 150 - 5 条) 绝大部分时间后端接口需要获取记录个数在 50 以内,所以效率提升在 100 倍左右

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值