• Mongdb 简单增删改查


    package test.com;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map.Entry;
    import java.util.Set;
    
    import org.bson.types.ObjectId;
    
    import com.mongodb.BasicDBObject;
    import com.mongodb.DB;
    import com.mongodb.DBCollection;
    import com.mongodb.DBCursor;
    import com.mongodb.DBObject;
    import com.mongodb.Mongo;
    import com.mongodb.MongoClient;
    import com.mongodb.MongoClientOptions;
    import com.mongodb.MongoCredential;
    import com.mongodb.ServerAddress;
    import com.mongodb.util.JSON;
    
    public class MongdbUtil {
    
        public static void main(String[] args) throws Exception {
            // insertInto();
            // delete();
            // updateData();
            searchData();
        }
    
        private static DB db;// 数据库
        private static DBCollection coll;// 文档集(表)
    
        public static void insertInto() throws Exception {
            MongoClient mongoClient = getMongoClient();
            db = mongoClient.getDB("testdb1");// 获取数据库
            coll = db.getCollection("mongodb16wifi");// 获取文档集,相当于表
    
            BasicDBObject document = new BasicDBObject();// 创建文档,相当于对象。文档集中存放大量文档(对象)
            document.put("database", "testdb");
            document.put("table", "hosting");
    
            BasicDBObject documentDetail = new BasicDBObject();// 对象中又包含对象
            documentDetail.put("records", "99");
            documentDetail.put("index", "vps_index1");
            documentDetail.put("active", "true");
            document.put("detail", documentDetail);
    
            coll.insert(document);
        }
    
        /**
         * 删除
         */
        public static void delete() throws Exception {
            MongoClient mongoClient = getMongoClient();
            db = mongoClient.getDB("testdb1");// 获取数据库
            coll = db.getCollection("mongodb16wifi");// 获取文档集,相当于表
    
            BasicDBObject data = new BasicDBObject();
            // 删除名称为lucy的记录
            data.put("table", "hosting");
            // 传入[空实例]删除所有
            coll.remove(data);
        }
    
        /**
         * 修改数据
         * 
         * @throws Exception
         */
        public static void updateData() throws Exception {
            MongoClient mongoClient = getMongoClient();
            db = mongoClient.getDB("testdb1");// 获取数据库
            coll = db.getCollection("mongodb16wifi");// 获取文档集,相当于表
    
            BasicDBObject query = new BasicDBObject();
            query.put("table", "hosting");
            // 这里的new_info对象一定要是find出的而不是new的,否则多字段的情况下就会丢失其它字段信息
            // findone,只查询表中第一个符合条件的对象
            DBObject new_info = coll.findOne(query);
    
            // 方法(优点,只需设置要修改的字段的值)
            DBObject obj = (DBObject) new_info.get("detail");
            obj.put("records", 1.5);
    
            coll.update(query, new_info);
        }
    
        /**
         * 查询数据
         * 
         * @throws Exception
         */
        public static void searchData() throws Exception {
            MongoClient mongoClient = getMongoClient();
            db = mongoClient.getDB("testdb1");// 获取数据库
            coll = db.getCollection("mongodb16wifi");// 获取文档集,相当于表
    
            // 获取数据库下所有的collection,不显示无数据的collection
            Set<String> colls = db.getCollectionNames();
            showData(colls);
    
            // 查询coll中全部记录
            DBCursor ite = coll.find();
            //showData(ite);
    
            // 获取第一条记录
            DBObject o = coll.findOne();
            System.out.println(o);
    
            // 统计colletion的数据条数
            System.out.println(coll.getCount());
    
            // 查询 name为jack的对象
            BasicDBObject query = new BasicDBObject();
            query.put("name", "jack");
            DBCursor it = coll.find(query);
            showData(it);
    
            // 查询age小于30,age不等于20的对象
            BasicDBObject query2 = new BasicDBObject();
            query2.put("age", new BasicDBObject("$lt", 30));
            query2.put("age", new BasicDBObject("$ne", 20));
            DBCursor cursor = coll.find(query2);
            /**
             * 遍历查询结果集。(这种遍历方式相比较Iterator遍历,简单且高效)
             */
            while (cursor.hasNext()) {
                DBObject dbObj = cursor.next();
                //System.out.println(dbObj.get("database"));//字符串格式
                System.out.println(dbObj.get("detail"));//json格式
            }
    
        }
    
        /**
         * 遍历显示结果
         * 
         * @param result
         */
        @SuppressWarnings("rawtypes")
        public static void showData(Iterable result) {
            Iterator it = result.iterator();
            while (it.hasNext()) {
                System.out.println(it.next());
            }
        }
    
        // 获取Mongdb 连接
        private static MongoClient getMongoClient() throws Exception {
            try {
                String sIp = "localhost";
                int iPort = 27017;
                String sUser = "testdb1u1";
                String sPasword = "xyz123";
                // ===================================================//
                List<ServerAddress> serverList = new ArrayList<ServerAddress>();
                serverList.add(new ServerAddress(sIp, iPort));
                // ===================================================//
                List<MongoCredential> mcList = new ArrayList<MongoCredential>();
                // 用户名,库名,密码
                mcList.add(MongoCredential.createCredential(sUser, "testdb1", sPasword.toCharArray()));
                // ===================================================//
                MongoClientOptions.Builder builder = MongoClientOptions.builder();
                // 与目标数据库能够建立的最大connection数量为50
                builder.connectionsPerHost(50);
                // 如果当前所有的connection都在使用中,则每个connection上可以有50个线程排队等待
                builder.threadsAllowedToBlockForConnectionMultiplier(50);
                // 故这里设置的maxWaitTime应该足够大,以免由于排队线程过多造成的数据库访问失败
                builder.maxWaitTime(1000 * 60 * 2);
                // 与数据库建立连接的timeout设置为1分钟
                builder.connectTimeout(1000 * 60 * 1);
                // ===================================================//
                MongoClientOptions mco = builder.build();
                return new MongoClient(serverList, mcList, mco);
            } catch (Exception e) {
                throw e;
            }
        }
    
    }
    

      

  • 相关阅读:
    java+根据多个url批量下载文件
    js拖拽文件夹上传
    php文件夹上传
    java上传大文件解决方案
    web文件系统
    WebService之CXF注解之三(Service接口实现类)
    oracle 推断字符是否为字母
    二分查找算法
    C# 杀掉后台进程
    (个人开源)ffpanel --ffmpeg的GUI,让ffmpeg离开黑黑的命令行
  • 原文地址:https://www.cnblogs.com/haorun/p/6381303.html
Copyright © 2020-2023  润新知