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

จะใช้ตัวดำเนินการ $slice เพื่อรับองค์ประกอบสุดท้ายของอาร์เรย์ใน MongoDB ได้อย่างไร


ในการรับองค์ประกอบสุดท้ายของอาร์เรย์ใน MongoDB ให้ใช้ไวยากรณ์ต่อไปนี้

db.yourCollectionName.find({},{yourArrayFieldName:{$slice:-1}});

ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน

>db.getLastElementOfArrayDemo.insertOne({"StudentName":"James","StudentMathScore":[78,68,98]});{ "acknowledged" :true, "insertedId" :ObjectId("5c9d2d71a629b87623db1b2e") }>db.getLastElementOfArrayDemo.insertOne({"StudentName":"Chris","StudentMathScore":[88,56,34]});{ "acknowledged" :true, "insertedId" :ObjectId("5c9d2d83a629b87623db1b2f")}> db.getLastElementOfArrayDemo.insertOne({"StudentName":"Larry","StudentMathScore":[99]});{ "acknowledged" :true, "insertedId" :ObjectId("5c9d2d8ea629b87623db1b30")}>dbArgetDemo.ElementOfinOnein {"StudentName":"Robert","StudentMathScore":[90,78,67,66,75,73]});{ "acknowledged" :true, "insertedId" :ObjectId("5c9d2dada629b87623db1b31")}

ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find()

> db.getLastElementOfArrayDemo.find().pretty();

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

{ "_id" :ObjectId("5c9d2d71a629b87623db1b2e"), "StudentName" :"James", "StudentMathScore" :[ 78, 68, 98 ]}{ "_id" :ObjectId("5c9d2dName3a629b87f" :"Chris", "StudentMathScore" :[ 88, 56, 34 ]}{ "_id" :ObjectId("5c9d2d8ea629b87623db1b30"), "StudentName" :"Larry", "StudentMathScore" :[ 99 ]}{ "_id" :ObjectId("5c9d2dada629b87623db1b31"), "StudentName" :"Robert", "StudentMathScore" :[ 90, 78, 67, 66, 75, 73 ]}

ต่อไปนี้เป็นแบบสอบถามเพื่อรับองค์ประกอบสุดท้ายของอาร์เรย์ใน MongoDB

> db.getLastElementOfArrayDemo.find({},{StudentMathScore:{$slice:-1}});

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

<ก่อน>{ "_id" :ObjectId("5c9d2d71a629b87623db1b2e"), "StudentName" :"James", "StudentMathScore" :[ 98 ] }{ "_id" :ObjectId("5c9d2d83a629bf87623db1b1b , "StudentMathScore" :[ 34 ] }{ "_id" :ObjectId("5c9d2d8ea629b87623db1b30"), "StudentName" :"Larry", "StudentMathScore" :[ 99 ] }{ "_id" :Object2d("5c9b87d31, StudentName" :"Robert","StudentMathScore" :[ 73 ] }