Mongodb自己封装的工具类

如何开启链接

链接本地的monogdb数据库

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

 

获取为itcast的数据库对象

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

 

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

MongoCollectioncollection =  db.getCollection("itcast");

 

 

Mongdb中的CURD操作

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

查询所有

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

FindIterable it = collection.find();

 

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

      MongoCursor 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

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

 

这类似与and name =‘yinchong’

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

 

执行条件查询

FindIterableit = collection.find(filter);

 

遍历结果  

MongoCursorcursor = 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

Mapmap = new HashMap();

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

       map.put("age", 24);

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

       Map hobby = newHashMap();

       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对象

Mapmap = new HashMap();

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(Mapmap)

 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 collection;


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

List array = new LinkedList();
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 Document transform2Doc(T bean) throws Exception{
Class clazz = bean.getClass();
HashMap data = new HashMap();
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  void  insertOne(T bean){
try {
collection.insertOne(transform2Doc(bean));
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 修改一条数据
* @throws IllegalAccessException 
* @throws IllegalArgumentException 
*/
public static void update(Map condition,T bean) throws Exception{
BasicDBObject filter = new BasicDBObject();
Set 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 newData = new HashMap();
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 condition){
BasicDBObject filter = new BasicDBObject();
Set 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 List findAll(Class clazz){
FindIterable it = collection.find();
MongoCursor cursor = it.iterator();
return data2Bean(clazz, cursor);
}


/**
* 查询指定数据
*/
public static List findCondition(Map condition,Class clazz){
BasicDBObject filter = new BasicDBObject();
Set 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 it = collection.find(filter);
MongoCursor cursor = it.iterator();
return data2Bean(clazz, cursor);
}

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

private static 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);
}

}

}

你可能感兴趣的:(Mongodb自己封装的工具类)