1. 程式人生 > >mongodb 增刪改查簡單封裝

mongodb 增刪改查簡單封裝


import java.io.FileInputStream;


import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSUploadStream;


import org.bson.Document;


import static com.mongodb.client.model.Filters.*;
/**
 * Created by shine on 2016/8/18.
 */
public class MongodbTemplete {
    private static MongoClient mongoClient = new MongoClient("0.0.0.0",27017);//你的IP以及埠配置
    public static  MongoDatabase db = mongoClient.getDatabase("healthData");
    
    public static GridFSBucket gridFSBucket = GridFSBuckets.create(db, "files");
    public static void insert(String Collection,Document document) {
        db.getCollection(Collection).insertOne(document);
    }


    public static void delete(String Collection,String key,String condition,String value) {
        db.getCollection(Collection).deleteMany(eq(key, value));
    }


    public static void update(String Collection,String key,String condition,String value,Document document) {
        db.getCollection(Collection).updateMany(eq(key, value),new Document("$set",document));


    }


    public static FindIterable<Document> query(String Collection,String key,String condition,Object value) {
        if(condition.equals("eq")) {
            return db.getCollection(Collection).find(eq(key, value));
        }
        else if(condition.equals("ne")){
            return db.getCollection(Collection).find(ne(key, value));
        }
        else if(condition.equals("gt")){
            return db.getCollection(Collection).find(gt(key, value));
        }
        else if(condition.equals("gte")){
            return db.getCollection(Collection).find(gte(key, value));
        }
        else if(condition.equals("lt")){
            return db.getCollection(Collection).find(lt(key, value));
        }
        else if(condition.equals("lte")){
            return db.getCollection(Collection).find(lte(key, value));
        }
        else if(condition.equals("where")){
            return db.getCollection(Collection).find(lte(key, value));
        }
        else {
          return null;
        }


    }
    
    public static void insertToGridFS(String fileName,byte[]data) {
     
    GridFSUploadStream uploadStream = gridFSBucket.openUploadStream(fileName);
uploadStream.write(data);
uploadStream.close();
 
    }






}