查找 MongoDB 集合中最旧/最年轻的帖子?
要查找 MongoDB 集合中最旧/最年轻的帖子,可以使用 sort()。假设你有一个文档,其中有一个字段“UserPostDate”,你需要获取最旧和最年轻的帖子。为此,我们首先创建一个包含文档的集合
>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") }
以下是使用 find() 方法显示集合中所有文档的查询
> db.getOldestAndYoungestPostDemo.find().pretty();
这将产生以下输出
{ "_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") }
以下是查找 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:00Z") }
广告