การดึงเอกสารเฉพาะด้วย limit() และ toArray()
หากต้องการดึงเอกสารเฉพาะ ให้ใช้ limit() ร่วมกับ toArray() เมธอด toArray() จะส่งคืน Array ที่มีเอกสารทั้งหมดจาก Cursor
สร้าง Collection พร้อมข้อมูล
> db.demo482.insertOne({_id:1,"StudentInformation":[{"Name":"Chris","Age":21}]});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo482.insertOne({_id:2,"StudentInformation":[{"Name":"Bob","Age":23}]});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo482.insertOne({_id:3,"StudentInformation":[{"Name":"David","Age":20}]});
{ "acknowledged" : true, "insertedId" : 3 }
แสดงเอกสารทั้งหมด
> db.demo482.find();
ผลลัพธ์:
{ "_id" : 1, "StudentInformation" : [ { "Name" : "Chris", "Age" : 21 } ] }
{ "_id" : 2, "StudentInformation" : [ { "Name" : "Bob", "Age" : 23 } ] }
{ "_id" : 3, "StudentInformation" : [ { "Name" : "David", "Age" : 20 } ] }
คิวรีดึงเอกสาร 2 รายการแรก
> db.demo482.find({}).limit(2).toArray();
ผลลัพธ์:
[
{
"_id" : 1,
"StudentInformation" : [
{
"Name" : "Chris",
"Age" : 21
}
]
},
{
"_id" : 2,
"StudentInformation" : [
{
"Name" : "Bob",
"Age" : 23
}
]
}
]