在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") }热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练