【问题标题】:Upgrading mongo search from runCommand to find using Java driver从 runCommand 升级 mongo search 以使用 Java 驱动程序进行查找
【发布时间】:2014-06-04 21:19:07
【问题描述】:

我正在使用 Java 驱动程序来运行一些 mongo 文本搜索。 我之前的代码的一个例子是(其中值是传入的字符串):

DBCollection coll = db.getCollection("testCollection");
//create the basic object
DBObject searchCmd = new BasicDBObject();
//create the search cmd
searchCmd.put("text", "testCollection"); // the name of the collection (string)
// define the search word
searchCmd.put("search", value); // the term to search for (string)
// define the return values
searchCmd.put("project", new BasicDBObject("score", 1).append("name", 1).append("path", 0).append("_id", 0));
// get the results
BasicDBObject commandResult = db.command(searchCmd);
// Just out the results key
BasicDBList results = (BasicDBList) commandResult.get("results");

然后我循环遍历“结果”,我得到每个它的分数

// Get the number ii
BasicDBObject element = (BasicDBObject) results.get(ii);
// Now get the score
double score = (double) element.get("score");

我想升级以使用 find,因为这似乎是 2.6 和更高版本更喜欢的方式。到目前为止,我有:

DBCollection coll = db.getCollection("testCollection");
BasicDBObject query = new BasicDBObject();
query.append("$text", new BasicDBObject("$search", value));
DBCursor cursor = coll.find(query);

但是,我不确定如何获得分数。 我尝试做类似的事情:

query.append("score", new BasicDBObject("$meta", "textScore"));

但这不起作用。我希望能够获得名称和分数,以便我可以将它们插入到一个新的集合中,该集合也将保存分数。

我可以通过以下方式轻松获得名称:

while (cursor.hasNext()) 
{
DBObject next = cursor.next();
String name = next.get("name").toString();
}

但是我如何获得分数呢?

【问题讨论】:

    标签: java mongodb


    【解决方案1】:

    我发现了这个有趣的页面:http://api.mongodb.org/java/current/

    看来 find 可以采用第二个具有字段的 DBObject。

    我创建了一个新对象:

    BasicDBObject fields = new BasicDBObject();
    fields.append("score", new BasicDBObject("$meta", "textScore"));
    

    我正在使用 find 调用:

    DBCursor cursor = coll.find(query, fields);
    

    现在我可以像得到名字一样得到分数了。

    【讨论】:

    • 如果您的问题得到解答,您甚至可以接受自己的帖子,向其他人展示您的解决方案有效。
    • 谢谢。我想我需要等几天才能做到这一点。
    • 我正在使用 mongo java 驱动程序 3.0 但没有 find() 函数需要两个 bson 对象。有什么替代方案吗?
    猜你喜欢
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    相关资源
    最近更新 更多