Có, bạn có thể sử dụng findOne (). Sau đây là cú pháp -
db.yourCollectionName.findOne();
Bạn cũng có thể sử dụng toArray () -
db.yourCollectionName.find().toArray();
Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> 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")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.betterFormatDemo.find();
Điều này sẽ tạo ra kết quả sau -
{ "_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 ] } Trường hợp 1 - Sử dụng findOne ().
Sau đây là truy vấn để hiển thị kết quả MongoDB ở định dạng tốt hơn -
> db.betterFormatDemo.findOne();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cd7ab826d78f205348bc640"),
"StudentName" : "Adam Smith",
"StudentScores" : [
98,
67,
89
]
} Trường hợp 2 - Sử dụng find (). ToArray ().
Sau đây là truy vấn để hiển thị kết quả MongoDB ở định dạng tốt hơn -
> db.betterFormatDemo.find().toArray();
Điều này sẽ tạo ra kết quả sau -
[
{
"_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
]
}
]