2015-10-30 47 views
3

我已經在某些集合上定義了一些簡單的遊標作爲find()。如何在cursor.ForEach中打印文檔?

cursor = db.students.find() 

學生有以下模式:

"_id" : 19, 
"name" : "Gisela Levin", 
"scores" : [ 
     { 
       "type" : "exam", 
       "score" : 44.51211101958831 
     }, 
     { 
       "type" : "quiz", 
       "score" : 0.6578497966368002 
     }, 
     { 
       "type" : "homework", 
       "score" : 93.36341655949683 
     }, 
     { 
       "type" : "homework", 
       "score" : 49.43132782777443 
     } 
] 

我想要遍歷光標和打印文檔。我嘗試這樣的:

cursor.forEach(function(o){print(o)}) 

它只打印此:

[目標對象]

如果我修改一個循環來選擇一些簡單的屬性它的工作原理:

cursor.forEach(function(o){print(o._id)}) 

雖然如果我將其更改爲打印分數,它會打印此:

[object Object],[object Object],[object Object],[object Object] 

是否有任何函數在mongodb shell中打印json文檔?

回答

5

我不知道爲什麼pretty不能適用於您的情況。

如果手動消耗光標,你需要使用printjson功能

db.collection.find().forEach(printjson) 

或過濾器表達

db.collection.find({}, { "scores": 1, "_id": 0 }).forEach(printjson) 
+0

你也可以使用函數'pretty':'db.collection.find({},{ 「算賬」:1, 「_id」:0}) .pretty()'。 – Jaco

+0

儘管這篇文章有點老了:你也可以用下面的表示法 'db.collection.find()。forEach(function(record){printjson(record.field)})' – Tobias

+0

這隻適用於你想要的在文檔中打印出單個字段。 @Tobias – styvane

0

下如果結果集是小,你可以出它一個集合,然後遍歷它。

List<org.bson.Document> resultList = (List<org.bson.Document>) mongoCollection.find() 
     .into(new ArrayList<org.bson.Document>()); 
resultList.forEach(doc -> printJson(doc)); 

而且printJson是

public static void printJson(org.bson.Document doc) { 
    JsonWriter jsonWriter = new JsonWriter(new StringWriter(), new JsonWriterSettings(JsonMode.SHELL, true)); 
    new DocumentCodec().encode(jsonWriter, doc, 
      EncoderContext.builder().isEncodingCollectibleDocument(true).build()); 
    System.out.println(jsonWriter.getWriter()); 
    System.out.flush(); 
}