Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

MongoDB 컬렉션에서 가장 오래된/가장 어린 게시물을 찾으시겠습니까?

<시간/>

MongoDB 컬렉션에서 가장 오래된/가장 어린 게시물을 찾으려면 sort()를 사용할 수 있습니다. "UserPostDate" 필드가 있는 문서가 있고 가장 오래된 게시물과 가장 최근 게시물을 가져와야 한다고 가정해 보겠습니다. 이를 위해 먼저 문서로 컬렉션을 생성하겠습니다.

>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Larry@123","UserName":"Larry","UserPostDate":new ISODate('2019-03-27 12:00:00')} );{ "승인됨" :true, "insertedId" :ObjectId("5c9a700f15e86fd1496b38ab")}>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Sam@897","UserName":"SamDate" 새로운 ISODate('2012-06-17 11:40:30')});{ "승인됨" :true, "insertedId" :ObjectId("5c9a703815e86fd1496b38ac")}>db.getOldestAndYoungestPostOne("" David@777","UserName":"David","UserPostDate":new ISODate('2018-01-31 10:45:35')});{ "승인됨":true, "insertedId":ObjectId(" 5c9a705e15e86fd1496b38ad")}>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Chris@909","UserName":"Chris","UserPostDate":새로운 ISODate('2017-044)-124:0 });{ "승인됨" :true, "insertedId" :ObjectId("5c9a708915e86fd1496b38ae")}

다음은 find() 메서드를 사용하여 컬렉션의 모든 문서를 표시하는 쿼리입니다.

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

그러면 다음과 같은 출력이 생성됩니다.

{ "_id":ObjectId("5c9a700f15e86fd1496b38ab"), "UserId":"Larry@123", "UserName":"Larry", "UserPostDate":ISODate("2019-03-27T12":00:0 )}{ "_id":ObjectId("5c9a703815e86fd1496b38ac"), "UserId":"Sam@897", "UserName":"Sam", "UserPostDate":ISODate("2012-06-17T11:40:30Z") }{ "_id":ObjectId("5c9a705e15e86fd1496b38ad"), "UserId":"David@777", "UserName":"David", "UserPostDate":ISODate("2018-01-31T10:45}:35Z") { "_id":ObjectId("5c9a708915e86fd1496b38ae"), "UserId":"Chris@909", "UserName":"Chris", "UserPostDate":ISODate("2017-04-14T04:12:04Z")} /사전> 

다음은 MongoDB 컬렉션에서 가장 오래된 게시물을 찾는 쿼리입니다.

> db.getOldestAndYoungestPostDemo.find().sort({ "UserPostDate" :1 }).limit(1);

그러면 다음과 같은 출력이 생성됩니다.

{ "_id":ObjectId("5c9a703815e86fd1496b38ac"), "UserId":"Sam@897", "UserName":"Sam", "UserPostDate":ISODate("2012-06-17T11:40:30Z ) }

다음은 MongoDB 컬렉션에서 가장 최근(최신) 게시물을 찾는 쿼리입니다.

> db.getOldestAndYoungestPostDemo.find().sort({ "UserPostDate" :-1 }).limit(1);

그러면 다음과 같은 출력이 생성됩니다.

{ "_id":ObjectId("5c9a700f15e86fd1496b38ab"), "UserId":"Larry@123", "UserName":"Larry", "UserPostDate":ISODate("2019-03-27T12":00:0 ) }