mongo shell提供了各种方法,例如ISODate(),以字符串或Date对象的形式返回日期。ISODate()构造函数使用ISODate()包装器返回Date对象。
让我们创建一个包含文档的集合-
> db.demo548.insertOne({"dueDate":new ISODate("2020-04-09 12:12:40")});{ "acknowledged" : true, "insertedId" : ObjectId("5e8e30499e5f92834d7f05de") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo548.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8e30499e5f92834d7f05de"), "dueDate" : ISODate("2020-04- 09T12:12:40Z") }
以下是从ISODate显示,月,日,周,年等的查询-
> db.demo548.aggregate( [ { $project: { Year: { $year: "$dueDate" }, Month: { $month: "$dueDate" }, Day: { $dayOfMonth: "$dueDate" }, Hour: { $hour: "$dueDate" }, Minutes: { $minute: "$dueDate" }, Seconds: { $second: "$dueDate" }, Milliseconds: { $millisecond: "$dueDate" }, DayOfYear: { $dayOfYear: "$dueDate" }, DayOfWeek: { $dayOfWeek: "$dueDate" }, Week: { $week: "$dueDate" } } } ] ).pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e8e30499e5f92834d7f05de"), "Year" : 2020, "Month" : 4, "Day" : 9, "Hour" : 12, "Minutes" : 12, "Seconds" : 40, "Milliseconds" : 0, "DayOfYear" : 100, "DayOfWeek" : 5, "Week" : 14 }