2

我的 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

请建议我

谢谢

4

1 回答 1

2

您可能必须深入挖掘返回的文档才能找到 Filename

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/

于 2013-06-28T21:26:27.493 回答