如何在 MongoDB 中使用 $slice 運算子獲取陣列的最後一個元素?


要獲取 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")
}
>db.getLastElementOfArrayDemo.insertOne({"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("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
   ]
}

以下是獲取 MongoDB 中陣列最後一個元素的查詢

> db.getLastElementOfArrayDemo.find({},{StudentMathScore:{$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 ] }

更新於: 30-Jul-2019

776 瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.