public static String mongodbCommandFind(MongoDatabase mongoDatabase, String queryGt ) throws Exception {
// String queryGt="db.getCollection(‘laAppInterface‘).find({‘invokeType‘:{$gt:1}},{‘appCode‘:1,‘invokeType‘:1, ‘Type‘:0})";
String queryReg = ".*\\.find\\(\\{(.+)\\}\\).*";
boolean isMatch = Pattern.matches(queryReg, queryGt);
if (!isMatch)
throw new Exception("此接口仅执行查询语句,且需要制定查询条件");
String tableRegExp = "getCollection\\(‘(\\w+?)‘\\)";
String queryRegExp = "\\.find\\((.*?)\\)";
String columnNameRegExp = "‘(\\w+?)‘:1";
String table = GetWithRegExps(queryGt, tableRegExp).get(0);
String query = GetWithRegExps(queryGt, queryRegExp).get(0);
String search = query.split("\\},")[0] + "}";
Document doc = new Document();
doc.append("find", table);
if (query.split("\\},").length > 1) {
String show = query.split("\\},")[1];
List<String> columnNames = GetWithRegExps(show, columnNameRegExp);
Document projection = new Document();
for (int i = 0; i < columnNames.size(); i++)
projection.put(columnNames.get(i), 1);
doc.append("projection", projection);
}
Document filter = Document.parse(search);
doc.append("filter", filter);
Document result = mongoDatabase.runCommand(doc);
return result.toJson();
}
private static List<String> GetWithRegExps(String s, String regExp) {
List<String> ss = new ArrayList<String>();
Pattern r = Pattern.compile(regExp);
// 现在创建 matcher 对象
Matcher m = r.matcher(s);
while (m.find()) {
ss.add(m.group(1));
}
return ss;
}
官方:https://docs.mongodb.com/manual/reference/command/find/#mongodb-dbcommand-dbcmd.find
java实现mongodb原生查询语句