mysql如何在Java中从mongodb集合返回数据
我有一个MongoDB数据库,其集合如下:
+----------+-------------+
| Field | Type |
+----------+-------------+
| sha | varchar(40) |
| filename | text |
+----------+-------------+
我还有一个MySQL数据库,它的表如下所示:
+----------+-------------+
| Field | Type |
+----------+-------------+
| sha | varchar(40) |
| filename | text |
+----------+-------------+
MySQL表中的SHA列包含50000条记录,而filename列是空的,我想从上面的MongoDB集合中获取。我想将此表中的SHA键与MongoDB集合中的SHA键进行比较。规则是,如果Mongo集合中存在SHA,则提取与该SHA密钥对应的文件名,并将其插入与本地MySQL中的SHA密钥对应的文件名字段
如何根据MySQL中的sha值返回文件名值?我只是不熟悉MongoDB查询的工作原理,我的MongoDB查询正确吗
我目前编写的代码如下所示:
//Get sha values from mysql and compare with the sha values in mongo and return corresponding filenames
Statement sqlStmt = mysqlConn.createStatement();
HashMap < String, String > shaFileNameMap = new HashMap < String, String > ();
//get sha values from local mysql
String shaQuery = "select * from commit_files";
ResultSet results = sqlStmt.executeQuery(shaQuery);
String sha = null;
String filename = null;
//Store returned sha values in a hashmap
while (results.next()) {
sha = results.getString("sha");
filename = results.getString("filename");
//Store in a map
shaFileNameMap.put(sha, filename);
}
for (Map.Entry < String, String > entry: shaFileNameMap.entrySet()) {
String key = entry.getKey();
//get all filenames matching the list from mongo db and insert into mysql
DBCollection commits = db.getCollection("commits");
DBObject query = new BasicDBObject();
BasicDBObject fields = new BasicDBObject("sha", "" + key + "");
DBCursor curs = commits.find(query, fields);
while (curs.hasNext()) {
DBObject o = curs.next();
//The code to insert filenames into Mysql goes here
}
}
# 1 楼答案
我的建议是:使用当前的API:
关键是,com。mongodb。客户模型Filters类保存所有您需要的内容,作为创建查询的快捷方式
API文档位于https://api.mongodb.com/java/current/com/mongodb/client/model/Filters.html