如何使用 mongoDB 比较查询运算符来处理 createdAt 日期?

How do I use mongoDB Comparison Query Operator's to work with createdAt dates?

我正在尝试编写一个 mongoDB 查询,它只会生成今天创建的对象。

在我输入 Chrome 浏览器的查询下方找到:

var currentDate = Date(); 
console.log(currentDate); 
Meteor.users.find({}, {createdAt: {$gte: currentDate}} ).fetch();

上面的代码产生:

Mon Oct 01 2018 14:35:58 GMT+0300 (East Africa Time)

(2) [{…}, {…}]

0: {_id: "REzQZdJJgjJ8q29eF", createdAt: Sat Sep 29 2018 10:48:51 GMT+0300 (East Africa Time)}
1: {_id: "JzgBEtSji9aYAQws6", createdAt: Mon Oct 01 2018 10:15:48 GMT+0300 (East Africa Time)}
length: 2
__proto__: Array(0)

注意两点。当前的给定日期是:Mon Oct 01 2018 14:35:58 GMT+0300 (East Africa Time),但查询忽略了 $gte 并输出了 $lte 的文档。

任何人都可以向我解释为什么这个 比较查询运算符 不起作用,也可以为这个查询提出一个可行的解决方案吗?

期待您的帮助

您正在创建一个 当前日期时间 变量并查找在它之后创建的文档 - 这几乎总是不会产生任何文档。您需要将日期缩短到今天 00:00:00。另请注意 new Date() 而不仅仅是 Date().

const currentDate = new Date();
currentDate.setHours(0,0,0,0);
Meteor.users.find({ createdAt: { $gte: currentDate }}).fetch();

最后请注意,这将为您提供当地时区的午夜,而不是祖鲁时间。