要获取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 ] }