如何使用Java中的$ query,$ hint或$ explain

时间:2017-06-21 05:19:18

标签: java mongodb mongodb-query

我正在使用MongoDB 3.4 我的方法是: -

MongoDatabase db = mongo.getDatabase(mongoDBLogs);
MongoIterable<String> allCollections = db.listCollectionNames();
str==FROM COLLECTION
MongoCollection<Document> table = db.getCollection(str);
MongoCursor<Document> cursor = table.find(queryForLogs).iterator();

问题出在OLD版本中我可以使用

DB db = mongo.getDB(mongoDBLogs);
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
DBCollection table = db.getCollection(s);
cursor = table.find().explain(); <<<<---- I have this explain method
AND ALSO I have
cursor = table.find().hint(indexKeys);<<<<---- I have this hint method
}

现在在3.4中我无法使用

访问这些选项
MongoCursor<Document> cursor = table.find(queryForLogs).explain() <-- this is type  FindIterable<Document>

OR

MongoCursor<Document> cursor = table.find(queryForLogs).hint(Some value); <---This is type  FindIterable<Document>

我参考链接: - see screenshot https://docs.mongodb.com/manual/reference/operator/meta/hint/

所以我做了另一种方法: -

    public  BasicDBObject generateQueryForSessionIDLogs(String service_name, String node_name, Date gtDate, Date lteDate, String session_id,List<String> logLevel, String errorMsg){
        BasicDBObject andQuery = new BasicDBObject();
        List<BasicDBObject> obj = new ArrayList<BasicDBObject>();

        //Use session to search. If session is unknown, start and end date must be provided
        if(!session_id.isEmpty() && session_id != null){
            String[] sessionarray = session_id.split(",");

            if(sessionarray.length == 1){
                Long val = Long.valueOf(sessionarray[0].trim()).longValue();
                obj.add(new BasicDBObject("s", val));

            } else{ 
                ArrayList<Long> vals =  new ArrayList<Long>();
                for(String strn : sessionarray){
                    vals.add(Long.valueOf(strn.trim()).longValue());
                }

                obj.add(new BasicDBObject("s", new BasicDBObject("$in", vals )));
            }
        }else{      
            if((gtDate != null) && (lteDate != null)){
                obj.add(new BasicDBObject("d",  new BasicDBObject("$gt", gtDate).append("$lte", lteDate)));
            }
        }

        if(!node_name.isEmpty()){
            obj.add(new BasicDBObject("i", node_name));
        }
        if(!service_name.isEmpty()){
            obj.add(new BasicDBObject("n", service_name ));
        }
        if(!errorMsg.isEmpty()) {
            obj.add(new BasicDBObject("m", Pattern.compile(errorMsg)));
        }

        if(!logLevel.isEmpty()){
//          obj.add(new BasicDBObject("r", new BasicDBObject("$in", logLevel )));
            obj.add(new BasicDBObject("r", logLevel.get(0) ));
        }

        if (obj.size() > 1){ //append 'AND' if there is >1 conditions
            andQuery.put("$and", obj);
        }

        BasicDBObject andQuery2 = new BasicDBObject();
        andQuery2.put("$query", andQuery);
        List<BasicDBObject> obj2 = new ArrayList<BasicDBObject>();
        obj2.add(new BasicDBObject("i",1));
        andQuery2.put("$hint", obj2);
        andQuery2.put("$explain", 1);
        logger.debug("Query String for Logs: " + andQuery2);
        return andQuery;
    }

我的最终查询如下: -

Query String for Logs: { "$query" : { "$and" : [ { "d" : { "$gt" : { "$date" : "2017-06-19T04:00:00.000Z"} , "$lte" : { "$date" : "2017-06-20T04:00:00.000Z"}}} , { "i" : "WM96BEPSIT02"}]} , "$hint" : [ { "i" : 1}] , "$explain" : 1}

错误: - Exception in thread "pool-2-thread-16" Exception in thread "pool-2-thread-15" com.mongodb.MongoQueryException: Query failed with error code 2 and error message 'unknown top level operator: $query' on server

还请建议您先调用索引值的其他方法。在我的情况下,所有搜索值都没有编入索引。

1 个答案:

答案 0 :(得分:0)

要将$hint$explain等内容发送到Java驱动程序,您实际使用.modifiers()中的FindIterable方法。例如:

MongoCursor<Document> iterator = collection.find()
    .modifiers(new Document("$explain",1)).iterator();

while (iterator.hasNext()) {
  System.out.println(iterator.next().toJson());
}

这将打印说明统计数据输出。

任何BsonDocument类型都可以作为参数提供。 有效列表位于核心文档中的Query Modifiers

一般来说,$query不是您实际使用的修饰符列表,因为您实际上是使用.find()的任何参数构造它。但是所有其他修饰符都适用于此处。