2013-06-28 48 views
2

獲得特定領域我在MongoDB的一些文件如下如何從monodb完整的測試搜索結果使用Java

{"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

請建議我

感謝

+0

System.out.println(commandResult.getString(「Description」)); –

+0

它返回空值 – user2522836

回答

2

你可能有挖掘返回的文檔到g等以文件名

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")); 
} 

另外,如果你只需要在文件名域中,你可能要添加項目選項searchCmd限制返回搜索結果中的字段數。請參閱以下鏈接瞭解文本命令返回的文檔詳細信息和項目選項。
http://docs.mongodb.org/manual/reference/command/text/

+0

嗨,感謝您的代碼,但它顯示空指針異常在這一行「for(Iterator < Object > it = results.iterator(); it.hasNext();)」,你能幫我在解決這個... – user2522836

+0

Sry我忘了啓用文本搜索,現在它的工作非常感謝你。 – user2522836

相關問題