gpt4 book ai didi

php - MongoDB:按日期查询

转载 作者:可可西里 更新时间:2023-11-01 09:59:52 25 4
gpt4 key购买 nike

在 MongoDB 数据库中,我有一个项目集合,每个项目都存储其创建日期。我需要按日期查询这个集合。我试过:

db.items.findOne({date:{new Date(1285947037*1000)}})

但它没有返回任何东西。我使用 PHP($date->sec,其中 $date 是数据库中的 MongoDate 对象)获得了时间戳。那么这样做的正确方法是什么?谢谢。

最佳答案

Date 构造函数需要一个以毫秒 为单位的时间戳。 1285947037 时间戳以 为单位,这就是您将其乘以 1000 的原因。

我的猜测是文档中的实际时间戳包含毫秒,例如1285947037461(注意末尾的 461)。您将秒数乘以 1000,得到 1285947037000。如您所见,这些时间戳不相等:

1285947037461 // actual timestamp in MongoDB
1285947037000 // value you calculated

问题在于 MongoDate 类:它失去了毫秒精度,正如您在 documentation 中看到的那样.这是引述:

[...] this means that any precision beyond milliseconds will be lost when the document is sent to/from the database.

要使用以秒为单位的时间戳来查找您要查找的文档,您需要这样的东西:

db.foo.findOne(function () {
// round the stored date to seconds and compare to timestamp
return parseInt(this.date / 1000) === 1285947037
})

您可以使用 myDateObject.getTime() 在控制台中获取以毫秒为单位的准确时间戳。

关于php - MongoDB:按日期查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4063076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com