【发布时间】:2020-12-20 05:48:11
【问题描述】:
我想计算当前处于活动状态的 resetPassword(用户架构中的子文档)代码的数量。要使代码处于活动状态,其到期日期必须大于当前日期。
这是我的用户架构。如果有人要求重置密码,我们会将一个新的{ code: X, expiresAt, createdAt } 对象推送到数组中。
id: { type: String, unique: true },
resetPassword: [
{
code: String,
expiresAt: Date,
createdAt: Date,
},
],
我在尝试对活动重置代码的总数进行 $sum 时遇到问题。这是我正在运行的返回空数组的查询...请注意,如果我要删除 resetPassword.expiresAt: { $gt: nowDateInMilliseconds() } 匹配部分,它将返回所有代码。我尝试将此匹配语句移出初始 $match 阶段,然后在 expiresAt 上进行展开和匹配,但这也不起作用。
[
{
$match: {
"id": userId,
'resetPassword.expiresAt': {
$gt: nowDateInMillisec(),
},
},
},
{
$group: {
_id: '$id',
totalValidResetCodes: {
$sum: {
$size: '$resetPassword',
},
},
},
},
]
这将返回一个空数组,即使我已将到期日期设置为将来的某个日期。
我还尝试了以下相同的结果(注意我是如何向管道添加 $unwind 和另一个 $match 的)
[
{
$match: {
"id": userId,
},
},
{
$unwind: '$resetPassword',
},
{
$match: {
'resetPassword.expiresAt': {
$gt: nowDateInMillisec(),
},
}
},
{
$group: {
_id: '$id',
totalValidResetCodes: {
$sum: {
$size: '$resetPassword',
},
},
},
},
]
-
nowDateInMillisec()- 这只是从纪元返回当前日期(以毫秒为单位)。
我做错了什么?
【问题讨论】:
-
可能是类型不匹配。如果您使用日期类型而不是毫秒,它的行为会有所不同吗?
-
@Joe You 美女!就是这样......我认为使用
milliseconds是可以的,Mongo 会在那里处理转换!如果您想添加您的答案,我会接受。 -
@Joe 当我在我的猫鼬模式中设置了
Date类型时,我是否正确地将日期插入为milliseconds?我应该使用Integer类型而不是使用Date类型吗?
标签: mongodb mongodb-query aggregation-framework