我们将printjson()
为此使用。首先让我们创建一个包含文档的集合-
> dbprintResultScriptDemoinsertOne({"StudentName":"John","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cf22c02b64a577be5a2bc0b") } > dbprintResultScriptDemoinsertOne({"StudentName":"Carol","StudentAge":20}); { "acknowledged" : true, "insertedId" : ObjectId("5cf22c09b64a577be5a2bc0c") } > dbprintResultScriptDemoinsertOne({"StudentName":"David","StudentAge":19}); { "acknowledged" : true, "insertedId" : ObjectId("5cf22c11b64a577be5a2bc0d") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> dbprintResultScriptDemofind();
这将产生以下文件-
{ "_id" : ObjectId("5cf22c02b64a577be5a2bc0b"), "StudentName" : "John", "StudentAge" : 21 } { "_id" : ObjectId("5cf22c09b64a577be5a2bc0c"), "StudentName" : "Carol", "StudentAge" : 20 } { "_id" : ObjectId("5cf22c11b64a577be5a2bc0d"), "StudentName" : "David", "StudentAge" : 19 }
以下是打印脚本结果的查询-
> var document=dbprintResultScriptDemofind(); > while (documenthasNext()) { printjson(documentnext()); }
这将产生以下文件-
{ "_id" : ObjectId("5cf22c02b64a577be5a2bc0b"), "StudentName" : "John", "StudentAge" : 21 } { "_id" : ObjectId("5cf22c09b64a577be5a2bc0c"), "StudentName" : "Carol", "StudentAge" : 20 } { "_id" : ObjectId("5cf22c11b64a577be5a2bc0d"), "StudentName" : "David", "StudentAge" : 19 }