如何只获取Mongodb文档中的特定字段?

时间:2016-06-13 14:44:39

标签: java mongodb mongodb-query

从system.profile集合我有这样的文件:

{
    "op" : "command",
    "ns" : "..",
    "command" : {
        "count" : "..",
        "query" : {
            "$and" : [ 
                ...
            ]
        }
    },
    "responseLength" : 48,
    "millis" : 18,
}

有些查询没有命令字段,而是有“查询”字段。我想检查'command'字段是否存在。如果是,则将其附加到我的Stringbuilder对象,如果不附加'query'。

更新
我试图按照Davide的建议使用Projection,但我仍然没有找到一种方法来检查查询是否存在,如果它确实存在则追加它。

DBCollection collection = mongoTemplate.getCollection("system.profile");
DBObject query = new BasicDBObject("command", new BasicDBObject("$exists",true));
BasicDBObject fields = new BasicDBObject("command",1).append("millis", 1).append("ts", 1);
DBCursor cursor = collection.find(query, fields);
 while(cursor.hasNext()) {
    sb.append(cursor.next());
    sb.append(System.getProperty("line.separator"));
    }
return sb;

}

1 个答案:

答案 0 :(得分:4)

您需要使用以下method

public DBCursor find(DBObject query, DBObject projection);

来自java doc

  

投影 - 指定MongoDB将从结果集中的文档返回哪些字段。