Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

ดึงเอกสารเฉพาะที่มีค่าอาร์เรย์ใน MongoD


ในการดึงเอกสารเฉพาะ ให้ใช้ limit() ร่วมกับ toArray() toArray() วิธีการส่งกลับอาร์เรย์ที่มีเอกสารทั้งหมดจากเคอร์เซอร์ ให้เราสร้างคอลเลกชันที่มีเอกสาร -

> 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 }

แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -

> db.demo482.find();

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

{ "_id" : 1, "StudentInformation" : [ { "Name" : "Chris", "Age" : 21 } ] }
{ "_id" : 2, "StudentInformation" : [ { "Name" : "Bob", "Age" : 23 } ] }
{ "_id" : 3, "StudentInformation" : [ { "Name" : "David", "Age" : 20 } ] }

ต่อไปนี้เป็นแบบสอบถามเพื่อดึงเอกสารเฉพาะด้วย limit() -

> db.demo482.find({}).limit(2).toArray();

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

[
   {
      "_id" : 1,
      "StudentInformation" : [
         {
            "Name" : "Chris",
            "Age" : 21
         }
      ]
   },
   {
      "_id" : 2,
      "StudentInformation" : [
         {
            "Name" : "Bob",
            "Age" : 23
         }
      ]
   }
]