怎樣才能以更加好的格式檢視 MongoDB 的結果?
是的,可以使用 findOne()。以下是語法 −
db.yourCollectionName.findOne();
也可以使用 toArray() −
db.yourCollectionName.find().toArray();
讓我們先使用文件建立一個集合 −
> db.betterFormatDemo.insertOne({"StudentName":"Adam Smith","StudentScores":[98,67,89]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7ab826d78f205348bc640") } > db.betterFormatDemo.insertOne({"StudentName":"John Doe","StudentScores":[67,89,56]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7ab936d78f205348bc641") } > db.betterFormatDemo.insertOne({"StudentName":"Sam Williams","StudentScores":[45,43,33]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7aba76d78f205348bc642") }
以下是使用 find() 方法從集合中顯示所有文件的查詢 −
> db.betterFormatDemo.find();
這將會生成以下輸出 −
{ "_id" : ObjectId("5cd7ab826d78f205348bc640"), "StudentName" : "Adam Smith", "StudentScores" : [ 98, 67, 89 ] } { "_id" : ObjectId("5cd7ab936d78f205348bc641"), "StudentName" : "John Doe", "StudentScores" : [ 67, 89, 56 ] } { "_id" : ObjectId("5cd7aba76d78f205348bc642"), "StudentName" : "Sam Williams", "StudentScores" : [ 45, 43, 33 ] }
情況 1 − 使用 findOne()。
以下是使用更好的格式顯示 MongoDB 結果的查詢 −
> db.betterFormatDemo.findOne();
這將會生成以下輸出 −
{ "_id" : ObjectId("5cd7ab826d78f205348bc640"), "StudentName" : "Adam Smith", "StudentScores" : [ 98, 67, 89 ] }
情況 2 − 使用 find().toArray()。
以下是使用更好的格式顯示 MongoDB 結果的查詢 −
> db.betterFormatDemo.find().toArray();
這將會生成以下輸出 −
[ { "_id" : ObjectId("5cd7ab826d78f205348bc640"), "StudentName" : "Adam Smith", "StudentScores" : [ 98, 67, 89 ] }, { "_id" : ObjectId("5cd7ab936d78f205348bc641"), "StudentName" : "John Doe", "StudentScores" : [ 67, 89, 56 ] }, { "_id" : ObjectId("5cd7aba76d78f205348bc642"), "StudentName" : "Sam Williams", "StudentScores" : [ 45, 43, 33 ] } ]
廣告