首页 > 数据库技术 > 详细

java实现mongodb原生查询语句

时间:2021-04-23 00:10:04      阅读:18      评论:0      收藏:0      [点我收藏+]
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原生查询语句

原文:https://www.cnblogs.com/diluckaya/p/14691250.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!