Computer >> Máy Tính >  >> Lập trình >> MongoDB

Tìm bài đăng cũ nhất / trẻ nhất trong bộ sưu tập MongoDB?

Để tìm bài đăng cũ nhất / trẻ nhất trong bộ sưu tập MongoDB, bạn có thể sử dụng sort (). Giả sử bạn có một tài liệu với trường “Ngày đăng ký người dùng” và bạn cần tải bài đăng cũ nhất và trẻ nhất. Đối với điều đó, trước tiên, chúng ta hãy tạo một bộ sưu tập với các tài liệu

>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Larry@123","UserName":"Larry","UserPostDate":new ISODate('2019-03-27 12:00:00')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a700f15e86fd1496b38ab")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Sam@897","UserName":"Sam","UserPostDate":new ISODate('2012-06-17 11:40:30')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a703815e86fd1496b38ac")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"David@777","UserName":"David","UserPostDate":new ISODate('2018-01-31 10:45:35')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a705e15e86fd1496b38ad")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Chris@909","UserName":"Chris","UserPostDate":new ISODate('2017-04-14 04:12:04')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a708915e86fd1496b38ae")
}

Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ()

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

Điều này sẽ tạo ra kết quả sau

{
   "_id" : ObjectId("5c9a700f15e86fd1496b38ab"),
   "UserId" : "Larry@123",
   "UserName" : "Larry",
   "UserPostDate" : ISODate("2019-03-27T12:00:00Z")
}
{
   "_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")
}

Sau đây là truy vấn để tìm bài đăng cũ nhất trong bộ sưu tập MongoDB

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

Điều này sẽ tạo ra kết quả sau

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

Sau đây là truy vấn để tìm bài đăng trẻ nhất (gần đây) trong bộ sưu tập MongoDB

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

Điều này sẽ tạo ra kết quả sau

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