首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Java中从mongodb集合返回数据

问如何在Java中从mongodb集合返回数据
EN

Stack Overflow用户
提问于 2016-09-11 19:01:29
回答 1查看 332关注 0票数 0

我有一个MongoDB数据库,其中有一个集合,如下所示:

代码语言:javascript
复制
+----------+-------------+
| Field    | Type        |
+----------+-------------+
| sha      | varchar(40) |
| filename | text        | 
+----------+-------------+

我还有一个MySQL数据库,其中有一个表,如下所示:

代码语言:javascript
复制
+----------+-------------+
| 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查询正确吗?

我当前编写的代码如下所示:

代码语言:javascript
复制
//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
  }
}
EN

回答 1

Stack Overflow用户

发布于 2016-09-12 13:50:46

我的建议是:使用当前的API:

代码语言:javascript
复制
...
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39435383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档