Đối với điều này, hãy sử dụng printjson. 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.cursorDemo.insertOne({"StudentFullName":"John Smith","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f0d08f9e6ff3eb0ce442")
}
> db.cursorDemo.insertOne({"StudentFullName":"John Doe","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f0df8f9e6ff3eb0ce443")
}
> db.cursorDemo.insertOne({"StudentFullName":"Carol Taylor","StudentAge":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444")
}
> db.cursorDemo.insertOne({"StudentFullName":"Chris Brown","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f0f88f9e6ff3eb0ce445")
} 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.cursorDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cc7f0d08f9e6ff3eb0ce442"),
"StudentFullName" : "John Smith",
"StudentAge" : 23
}
{
"_id" : ObjectId("5cc7f0df8f9e6ff3eb0ce443"),
"StudentFullName" : "John Doe",
"StudentAge" : 21
}
{
"_id" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444"),
"StudentFullName" : "Carol Taylor",
"StudentAge" : 20
}
{
"_id" : ObjectId("5cc7f0f88f9e6ff3eb0ce445"),
"StudentFullName" : "Chris Brown",
"StudentAge" : 24
} Sau đây là truy vấn để lặp lại và in tài liệu với printjson -
> db.cursorDemo.find().forEach(printjson);
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cc7f0d08f9e6ff3eb0ce442"),
"StudentFullName" : "John Smith",
"StudentAge" : 23
}
{
"_id" : ObjectId("5cc7f0df8f9e6ff3eb0ce443"),
"StudentFullName" : "John Doe",
"StudentAge" : 21
}
{
"_id" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444"),
"StudentFullName" : "Carol Taylor",
"StudentAge" : 20
}
{
"_id" : ObjectId("5cc7f0f88f9e6ff3eb0ce445"),
"StudentFullName" : "Chris Brown",
"StudentAge" : 24
} Sau đây là truy vấn thứ hai nếu chúng ta muốn các trường cụ thể chỉ như các trường “StudentFullName” và “StudentAge” -
> db.cursorDemo.find({}, { "StudentFullName": 1,"StudentAge":1, "_id": 0 }).forEach(printjson) Điều này sẽ tạo ra kết quả sau -
{ "StudentFullName" : "John Smith", "StudentAge" : 23 }
{ "StudentFullName" : "John Doe", "StudentAge" : 21 }
{ "StudentFullName" : "Carol Taylor", "StudentAge" : 20 }
{ "StudentFullName" : "Chris Brown", "StudentAge" : 24 }