如何根据日期记录从MongoDB集合中获取最新的数据集?
sort()
和-1。对于仅单个数据(即文档),请使用LIMIT(1)。让我们创建一个包含文档的集合-> db.demo521.insertOne({"PurchaseDate":new ISODate("2019-01-10"),"ProductName":"Product-1"});{ "acknowledged" : true, "insertedId" : ObjectId("5e89a1acb3fbf26334ef6117") } > db.demo521.insertOne({"PurchaseDate":new ISODate("2020-04-05"),"ProductName":"Product-10"});{ "acknowledged" : true, "insertedId" : ObjectId("5e89a1b9b3fbf26334ef6118") } > db.demo521.insertOne({"PurchaseDate":new ISODate("2010-05-08"),"ProductName":"Product-4"});{ "acknowledged" : true, "insertedId" : ObjectId("5e89a1c8b3fbf26334ef6119") } > db.demo521.insertOne({"PurchaseDate":new ISODate("2020-02-21"),"ProductName":"Product-3"});{ "acknowledged" : true, "insertedId" : ObjectId("5e89a1d7b3fbf26334ef611a") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo521.find();
这将产生以下输出-
{ "_id" : ObjectId("5e89a1acb3fbf26334ef6117"), "PurchaseDate" : ISODate("2019-01-10T00:00:00Z"), "ProductName" : "Product-1" } { "_id" : ObjectId("5e89a1b9b3fbf26334ef6118"), "PurchaseDate" : ISODate("2020-04-05T00:00:00Z"), "ProductName" : "Product-10" } { "_id" : ObjectId("5e89a1c8b3fbf26334ef6119"), "PurchaseDate" : ISODate("2010-05-08T00:00:00Z"), "ProductName" : "Product-4" } { "_id" : ObjectId("5e89a1d7b3fbf26334ef611a"), "PurchaseDate" : ISODate("2020-02-21T00:00:00Z"), "ProductName" : "Product-3" }
以下是查询以获取基于日期的最新数据集-
> db.demo521.find().sort({"PurchaseDate": -1}).limit(1);
这将产生以下输出-
{ "_id" : ObjectId("5e89a1b9b3fbf26334ef6118"), "PurchaseDate" : ISODate("2020-04-05T00:00:00Z"), "ProductName" : "Product-10" }