【问题标题】:How do I use mongoDB Comparison Query Operator's to work with createdAt dates?如何使用 mongoDB 比较查询运算符来处理 createdAt 日期?
【发布时间】:2018-10-01 11:53:28
【问题描述】:

我正在尝试编写一个只会产生今天创建的对象的 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 的文档。

谁能向我解释一下为什么这个比较查询运算符不起作用,还请提出一个可行的解决方案来解决这个查询?

期待您的帮助

【问题讨论】:

  • find(criteria, options) 不是反过来吗?
  • @Geoffroy 我认为您的解决方案有点不正统,但我还是继续尝试了一下。我希望这就是你的意思:'Meteor.users.find({createdAt: {$lte: date}}, {}).fetch()';不幸的是,这根本不会产生任何东西。如果这不是您的意思,请在代码中详细说明。
  • 这不是非正统的,正如接受的答案所示

标签: mongodb date datetime meteor


【解决方案1】:

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

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

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

【讨论】:

猜你喜欢
  • 2019-03-10
  • 2018-03-19
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
相关资源
最近更新 更多