簡體   English   中英

如何僅從Mongodb文檔中獲取特定字段?

[英]How to get only specific fields from Mongodb document?

從system.profile集合中,我有這樣的文檔:

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

有些查詢沒有命令字段,而是有“查詢”字段。 我想檢查“命令”字段是否存在。 如果確實存在,則將其附加到我的Stringbuilder對象中;如果沒有,則附加“查詢”。

更新:
我曾嘗試使用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;

}

您需要使用以下方法

public DBCursor find(DBObject query, DBObject projection);

java doc

projection-指定MongoDB從結果集中的文檔中返回哪些字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM