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