要将日期转换为MongoDB中的时间戳,请使用aggregate()
。让我们创建一个包含文档的集合-
> db.demo93.insertOne({"UserName":"Chris","ArrivalDate":new ISODate("2020-10-01")}); { "acknowledged" : true, "insertedId" : ObjectId("5e2d4b6479799acab037af68") } > db.demo93.insertOne({"UserName":"David","ArrivalDate":new ISODate("2019-12-31")}); { "acknowledged" : true, "insertedId" : ObjectId("5e2d4b7379799acab037af69") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo93.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2d4b6479799acab037af68"), "UserName" : "Chris", "ArrivalDate" : ISODate("2020-10-01T00:00:00Z") } { "_id" : ObjectId("5e2d4b7379799acab037af69"), "UserName" : "David", "ArrivalDate" : ISODate("2019-12-31T00:00:00Z") }
以下是在MongoDB中将日期转换为时间戳的查询-
> db.demo93.aggregate([ ... { "$match": { "UserName": "Chris" }}, ... { "$addFields": { ... "timestamp": { "$toLong": "$ArrivalDate" } ... }} ... ]);
这将产生以下输出-
{ "_id" : ObjectId("5e2d4b6479799acab037af68"), "UserName" : "Chris", "ArrivalDate" : ISODate("2020-10-01T00:00:00Z"), "timestamp" : NumberLong("1601510400000") }