ได้ คุณสามารถใช้ 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
]
}
]