Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB find() 결과 세트에서 마지막 문서를 확인하는 방법

MongoDB find() 결과에서 마지막 문서 확인하기

MongoDB에서 find() 메서드로 조회한 결과 세트 중 마지막 문서를 확인하려면 sort() 메서드를 내림차순으로 정렬하여 사용하면 됩니다. 기본 문법은 다음과 같습니다.

db.yourCollectionName.find().sort( { _id : -1 } ).limit(1).pretty();

_id 값은 ObjectId 기반으로 생성 시각이 반영되어 시간 순서대로 증가하는 특성이 있습니다. 따라서 _id를 내림차순(-1)으로 정렬하면 가장 늦게 삽입된 문서가 첫 번째 위치에 오게 되고, 여기에 limit(1)을 적용하면 마지막 문서 하나만 손쉽게 가져올 수 있습니다.

예제용 컬렉션 만들기

위 문법을 실제로 이해하기 위해 문서가 담긴 컬렉션을 먼저 생성해 보겠습니다. 다음은 컬렉션에 문서를 삽입하는 쿼리입니다.

> db.identifyLastDocuementDemo.insertOne({"UserName":"Larry","UserAge":24,"UserCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a2ff4cf1f7a64fa4df57")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Chris","UserAge":21,"UserCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a3094cf1f7a64fa4df58")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"David","UserAge":25,"UserCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a3174cf1f7a64fa4df59")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Sam","UserAge":26,"UserCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a3224cf1f7a64fa4df5a")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Mike","UserAge":27,"UserCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a32e4cf1f7a64fa4df5b")
}
> db.identifyLastDocuementDemo.insertOne({"UserName":"Carol","UserAge":28,"UserCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c94a33c4cf1f7a64fa4df5c")
}

컬렉션의 전체 문서 조회

find() 메서드를 사용해 컬렉션의 모든 문서를 출력해 보겠습니다. 쿼리는 다음과 같습니다.

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

실행 결과는 아래와 같습니다.

{
   "_id" : ObjectId("5c94a2ff4cf1f7a64fa4df57"),
   "UserName" : "Larry",
   "UserAge" : 24,
   "UserCountryName" : "US"
}
{
   "_id" : ObjectId("5c94a3094cf1f7a64fa4df58"),
   "UserName" : "Chris",
   "UserAge" : 21,
   "UserCountryName" : "UK"
}
{
   "_id" : ObjectId("5c94a3174cf1f7a64fa4df59"),
   "UserName" : "David",
   "UserAge" : 25,
   "UserCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c94a3224cf1f7a64fa4df5a"),
   "UserName" : "Sam",
   "UserAge" : 26,
   "UserCountryName" : "US"
}
{
   "_id" : ObjectId("5c94a32e4cf1f7a64fa4df5b"),
   "UserName" : "Mike",
   "UserAge" : 27,
   "UserCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"),
   "UserName" : "Carol",
   "UserAge" : 28,
   "UserCountryName" : "UK"
}

마지막 문서를 조회하는 쿼리

이제 find() 결과 세트에서 마지막 문서를 확인하는 쿼리입니다.

> db.identifyLastDocuementDemo.find().sort( { _id : -1 } ).limit(1).pretty();

출력 결과는 다음과 같습니다.

{
   "_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"),
   "UserName" : "Carol",
   "UserAge" : 28,
   "UserCountryName" : "UK"
}

결과를 보면 가장 마지막에 삽입된 Carol의 문서가 반환된 것을 확인할 수 있습니다. 이처럼 sort()limit()을 조합하면 별도의 복잡한 로직 없이도 find() 결과에서 마지막 문서를 간단하게 얻을 수 있습니다.