如何在MongoDB shell中列印文件的值?
為此,使用forEach()的概念。我們首先使用文件建立一個集合 -
> db.printDocuementValueDemo.insertOne({"InstructorName":"John Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd6804f7924bb85b3f48950") } > db.printDocuementValueDemo.insertOne({"InstructorName":"Sam Williams"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd680577924bb85b3f48951") } > db.printDocuementValueDemo.insertOne({"InstructorName":"David Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd680637924bb85b3f48952") }
以下是使用find()方法顯示集合中所有文件的查詢 -
> db.printDocuementValueDemo.find().pretty();
這將產生以下輸出 -
{ "_id" : ObjectId("5cd6804f7924bb85b3f48950"), "InstructorName" : "John Smith" } { "_id" : ObjectId("5cd680577924bb85b3f48951"), "InstructorName" : "Sam Williams" } { "_id" : ObjectId("5cd680637924bb85b3f48952"), "InstructorName" : "David Miller" }
以下是列印MongoDB shell中文件值的查詢 -
> db.printDocuementValueDemo.find( { _id : ObjectId("5cd680577924bb85b3f48951") }, {InstructorName: 1, _id:0} ).forEach(function(myDocument) { print(myDocument.InstructorName); });
這將產生以下輸出 -
Sam Williams
廣告