【问题标题】:how to get particular field from the result of full test search in monodb using java如何使用java从mongodb中的完整测试搜索结果中获取特定字段
【发布时间】:2013-06-26 03:46:00
【问题描述】:

我的 mongodb 中有一些文档如下

{"Filename":"PHP Book.pdf","Author":"John" ,"Description":"This is my PHP Book"} 
{"Filename":"Java Book.html" ,"Author":"Paul" ,"Description":"This is my JAVA Book"}
{"Filename":".NET Book.doc" ,"Author":"James" ,"Description":"This is my .NET Book"}

我在描述字段上创建了文本索引,下面是我在描述字段上进行全文搜索的代码。

            m = new Mongo("10.0.0.26", 27017);
            DB db = m.getDB("soft") ;
            DBCollection col = db.getCollection("pocnew") ;
            String collection = col.toString();
            DBObject searchCmd = new BasicDBObject();
            searchCmd.put("text", collection);  
            searchCmd.put("search", "php"); 
            CommandResult commandResult = db.command(searchCmd);
            System.out.println(commandResult); 

我得到以下结果

{ "serverUsed" : "/10.0.0.26:27017" , "queryDebugString" : "php||||||" , "language" : "english" , "results" : [ { "score" : 0.5833333333333334 , "obj" : { "_id" : { "$oid" : "51cd7d302d45471420c1132b","Filename":"PHP Book.pdf","Author":"John" ,"Description":"This is my PHP Book"}]}}

我的要求是只显示文件名字段值,即只显示PHP Book.pdf

请给我建议

谢谢

【问题讨论】:

  • System.out.println(commandResult.getString("Description"));
  • 它返回空值

标签: java mongodb search full-text-search


【解决方案1】:

您可能需要仔细研究返回的文档才能找到文件名

CommandResult commandResult = db.command(searchCmd);
BasicDBList results = (BasicDBList)commandResult.get("results");
for( Iterator< Object > it = results.iterator(); it.hasNext(); )
{
    BasicDBObject result  = (BasicDBObject) it.next();
    BasicDBObject dbo = (BasicDBObject) result.get("obj");
    System.out.println(dbo.getString("Filename"));
}

另外,如果你只需要 Filename 字段,你可能需要在 searchCmd 中添加 project 选项来限制搜索结果中返回的字段数量。有关文本命令返回的文档详细信息和项目选项,请参见以下链接。
http://docs.mongodb.org/manual/reference/command/text/

【讨论】:

  • 嗨,谢谢你的代码,但它在这一行显示空指针异常“for(Iterator it = results.iterator(); it.hasNext(); )”,你能请帮我解决这个问题...
  • 对不起,我忘了启用文本搜索,现在它可以工作了,非常感谢。
猜你喜欢
  • 2019-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 1970-01-01
  • 1970-01-01
  • 2015-01-02
  • 2019-02-11
相关资源
最近更新 更多