java mongodb 使用MongoCollection,BasicDBObject 條件查詢


廢話不說,上代碼

 //鏈接數據庫
        MongoClient mongoClient = new MongoClient( "172.26.xxx.xxx" , 27017 );

        MongoDatabase mongoDatabase =mongoClient.getDatabase("xxxx");

        MongoCollection<Document> collection = mongoDatabase.getCollection("test_logs");

        //加入查詢條件
        BasicDBObject query = new BasicDBObject();
        //時間區間查詢 記住如果想根據這種形式進行時間的區間查詢 ,存儲的時候 記得把字段存成字符串,就按yyyy-MM-dd HH:mm:ss 格式來
        query.put("times", new BasicDBObject("$gte", "2018-06-02 12:20:00").append("$lte","2018-07-04 10:02:46"));
        //模糊查詢
        Pattern pattern = Pattern.compile("^.*王.*$", Pattern.CASE_INSENSITIVE);
        query.put("userName", pattern);
        //精確查詢
        query.put("id", "11");
        //skip 是分頁查詢,從第0條開始查10條數據。 Sorts是排序用的。有descending 和ascending
        MongoCursor<Document> cursor = collection.find(query).sort(Sorts.orderBy(Sorts.descending("times"))).skip(0).limit(10).iterator();//
        int unm=0;
        try {
            while (cursor.hasNext()) {
                UserBehaviorLogs userBehaviorLogs = new UserBehaviorLogs();
                //查詢出的結果轉換成jsonObject,然后進行封裝或者直接返回給前端處理。我這是封裝成對象了
                JSONObject jsonObject = JSONObject.parseObject( cursor.next().toJson().toString());
                userBehaviorLogs.setId(jsonObject.getString("id"));//id
                userBehaviorLogs.setUserId(jsonObject.getString("userId"));//用戶id
                userBehaviorLogs.setUserName(jsonObject.getString("userName"));//用戶名稱
                userBehaviorLogs.setParams(jsonObject.getString("params"));//參數
                userBehaviorLogs.setException(jsonObject.getString("Exception"));//異常信息
                userBehaviorLogs.setTimes(jsonObject.getString("times")+"");//創建時間
                unm++;
                System.out.println(unm+"="+userBehaviorLogs.getTimes()+"==="+userBehaviorLogs.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cursor.close();
        }

其中時間時間區間查詢 被坑了一把。后來直接改成字符串格式的了(yyyy-MM-dd HH:mm:ss)。

代碼直接拿過去就能用。

 

 本博客是本人原創 未經允許不得轉載 謝謝。

  鏈接地址:http://www.cnblogs.com/richard-ju/p/L2018006.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM