MongoDB-এ অ্যারের শেষ এলিমেন্ট বা শেষ Nটি এলিমেন্ট পেতে $slice অপারেটর باরেটিভ ভ্যালু ব্যবহার করা হয়।
সিনট্যাক্স
> 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") }
> db.getLastElementOfArrayDemo.insertOne({"StudentName":"Robert","StudentMathScore":[90,78,67,66,75,73]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c9d2dada629b87623db1b31") }
সকল ডকুমেন্ট দেখা
{ "_id" : ObjectId("5c9d2d71a629b87623db1b2e"), "StudentName" : "James", "StudentMathScore" : [ 78, 68, 98 ] }
{ "_id" : ObjectId("5c9d2d83a629b87623db1b2f"), "StudentName" : "Chris", "StudentMathScore" : [ 88, 56, 34 ] }
{ "_id" : ObjectId("5c9d2d8ea629b87623db1b30"), "StudentName" : "Larry", "StudentMathScore" : [ 99 ] }
{ "_id" : ObjectId("5c9d2dada629b87623db1b31"), "StudentName" : "Robert", "StudentMathScore" : [ 90, 78, 67, 66, 75, 73 ] }
শেষ ১টি এলিমেন্ট পাওয়া ($slice: -1)
{ "_id" : ObjectId("5c9d2d71a629b87623db1b2e"), "StudentName" : "James", "StudentMathScore" : [ 98 ] }
{ "_id" : ObjectId("5c9d2d83a629b87623db1b2f"), "StudentName" : "Chris", "StudentMathScore" : [ 34 ] }
{ "_id" : ObjectId("5c9d2d8ea629b87623db1b30"), "StudentName" : "Larry", "StudentMathScore" : [ 99 ] }
{ "_id" : ObjectId("5c9d2dada629b87623db1b31"), "StudentName" : "Robert", "StudentMathScore" : [ 73 ] }
$slice প্যারামিটার গাইড
| মান | ফলাফল |
|---|---|
$slice: 3 | প্রথম ৩টি এলিমেন্ট |
$slice: -3 | শেষ ৩টি এলিমেন্ট |
$slice: [skip, limit] | skip বাদ দিয়ে limit সংখ্যক |
$slice: [-10, 5] | শেষ ১০টি থেকে ৫টি |
এগْرিগেশনে $arrayElemAt (বিকল্প)
সুপারিশ
সহজ প্রজেকশনের জন্য
find()-এ$sliceব্যবহার করুন। জটিল লজিকের জন্য এগْرিগেশন পাইপলাইন ব্যবহার করুন।