让我们创建一个包含文档的集合-
> db.demo344.insertOne({"startDate":"2020-02-24 10:50:00", "endDate":"2020-02-24 11:50:00"}); { "acknowledged" : true, "insertedId" : ObjectId("5e53f52cf8647eb59e5620aa") } > db.demo344.insertOne({"startDate":"2020-02-24 08:00:00", "endDate":"2020-02-24 11:50:50"}); { "acknowledged" : true, "insertedId" : ObjectId("5e53f53df8647eb59e5620ab") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo344.find();
这将产生以下输出-
{ "_id" : ObjectId("5e53f52cf8647eb59e5620aa"), "startDate" : "2020-02-24 10:50:00", "endDate" : "2020-02-24 11:50:00" } { "_id" : ObjectId("5e53f53df8647eb59e5620ab"), "startDate" : "2020-02-24 08:00:00", "endDate" : "2020-02-24 11:50:50" }
以下是查询时间最长的对象的方法-
> db.demo344.aggregate([ ... { $addFields: { ... longestTime: { $subtract: [ { $toDate: "$endDate" }, { $toDate: "$startDate" } ] } ... } }, ... { $sort: { longestTime: -1 } }, ... { $limit: 1 } ... ])
这将产生以下输出-
{ "_id" : ObjectId("5e53f53df8647eb59e5620ab"), "startDate" : "2020-02-24 08:00:00", "endDate" : "2020-02-24 11:50:50", "longestTime" : NumberLong(13850000) }