要按时间戳排序,请在MongoDB中使用sort()。让我们创建一个包含文档的集合-
> db.demo737.insertOne({"timestamp" : new ISODate("2020-04-01" )}); { "acknowledged" : true, "insertedId" : ObjectId("5ead682157bb72a10bcf065c") } > db.demo737.insertOne({"timestamp" : new ISODate("2020-10-31" )}); { "acknowledged" : true, "insertedId" : ObjectId("5ead682757bb72a10bcf065d") } > db.demo737.insertOne({"timestamp" : new ISODate("2020-05-02" )}); { "acknowledged" : true, "insertedId" : ObjectId("5ead682a57bb72a10bcf065e") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo737.find();
这将产生以下输出-
{ "_id" : ObjectId("5ead682157bb72a10bcf065c"), "timestamp" : ISODate("2020-04-01T00:00:00Z") } { "_id" : ObjectId("5ead682757bb72a10bcf065d"), "timestamp" : ISODate("2020-10-31T00:00:00Z") } { "_id" : ObjectId("5ead682a57bb72a10bcf065e"), "timestamp" : ISODate("2020-05-02T00:00:00Z") }
以下是按时间戳排序的查询(降序)-
> db.demo737.find().sort({"timestamp":-1});
这将产生以下输出-
{ "_id" : ObjectId("5ead682757bb72a10bcf065d"), "timestamp" : ISODate("2020-10-31T00:00:00Z") } { "_id" : ObjectId("5ead682a57bb72a10bcf065e"), "timestamp" : ISODate("2020-05-02T00:00:00Z") } { "_id" : ObjectId("5ead682157bb72a10bcf065c"), "timestamp" : ISODate("2020-04-01T00:00:00Z") }