我有一个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值返回文件名值?我只是不熟悉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
}
}
答案 0 :(得分:0)
我的建议:使用当前的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