자바 에서 mongodb 는 MongoCollection 과 Basic DBObject 조건 을 사용 하여 조회 합 니 다.

1999 단어 SpringBoot
본문https://www.cnblogs.com/richard-ju/p/L2018006.html
MongoClient mongoClient = new MongoClient( "172.26.xxx.xxx" , 27017 );
MongoDatabase mongoDatabase =mongoClient.getDatabase("xxxx");
MongoCollection 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 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();
}

좋은 웹페이지 즐겨찾기