我有一个MongoDB数据库,其中有一个集合,如下所示:
+----------+-------------+
| Field | Type |
+----------+-------------+
| sha | varchar(40) |
| filename | text |
+----------+-------------+我还有一个MySQL数据库,其中有一个表,如下所示:
+----------+-------------+
| Field | Type |
+----------+-------------+
| sha | varchar(40) |
| filename | text |
+----------+-------------+MySQL表中的SHA列包含50000条记录,而filename列为空,这是我希望从上面的MongoDB集合中获得的。我想将此表中的SHA键与MongoDB集合中的SHA键进行比较。规则需要是,如果SHA存在于Mongo集合中,则拉取与该SHA密钥相对应的文件名,并将其插入到本地MySQL中与该SHA密钥相对应的文件名字段中。
如何根据MySQL中的sha值返回filename值?我只是不熟悉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
}
}发布于 2016-09-12 13:50:46
我的建议是:使用当前的API:
...
MongoClient client = new MongoClient();
MongoCollection<Document> coll = client .getDatabase("xyz").getCollection("myColl");
...
// in the query loop:
FindIterable<Document> res = coll.find(Filters.eq("sha", key);
// and go through the find iterable which has 0 to many entries关键的一点是,com.mongodb.client.model.Filters类将您需要的所有内容都作为创建查询的快捷方式。
https://api.mongodb.com/java/current/com/mongodb/client/model/Filters.html上的API-doc
https://stackoverflow.com/questions/39435383
复制相似问题