我正在尝试编写一个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();
最后请注意,这将为您提供当地时区的午夜,而不是祖鲁时间。