如何在 Mongodb 过滤器中使用比较

How to use comparison in Mongodb filter

上下文: 我正在制作一个网站,用户可以在其中创建帐户。然后他们必须通过打开验证电子邮件来验证他们的帐户。我正在使用 Node.js 和 Mongodb.

我要做什么:如果用户在过去 24 小时内未验证其帐户,则删除其帐户。

要删除的示例帐户

{
    created: 3294038434,
    notValid: "dslafjksdfkj"
}

不要删除的示例帐户:

{
    created: 203498324,
    notValid: false
}

created 键将日期存储为 number。 如果 notValidfalse,则该帐户已通过验证。如果notValidstring,则该账号尚未验证,该字符串代表验证码。

有没有办法让用户 deleteMany() 拥有类似这样的过滤器?

{
   Date.now() > created + 1000 * 60 * 60 * 24 && typeof(notValid) == "string"
}

我知道我可以读取每个用户然后执行逻辑,但是有没有办法让 mongodb 为我执行逻辑/过滤器?

mongo shell 开始,让我们获取这三个输入文档:

{ "_id" : 2, "created" : 1574831443519, "notValid" : "dslafjksdfkj-abc" }
{ "_id" : 3, "created" : 1574817043519, "notValid" : true }
{ "_id" : 1, "created" : 1574817043519, "notValid" : "abc-111" }

为 select 文档的查询创建过滤器,条件为:

Date.now() > created + 1000 * 60 * 60 * 24 && typeof(notValid) == "string"

var queryFilter = { $cond: {
                       if: { $and: [
                                     { $eq: [ { $type: "$notValid"}, "string" ] },
                                     { $gt: [ new Date(), { $toDate: { $add: [ "$created", 86400000 ] } } ] }
                                    ]
                            },
                        then: true,
                        else: false
                     }
};

查询db.colln.find( { $expr: { $eq: [ queryFilter, true ] } } )returns文档:

{ "_id" : 1, "created" : 1574817043519, "notValid" : "abc-111" }

正在应用查询过滤器删除匹配的文档:

db.colln.deleteMany( { $expr: { $eq: [ queryFilter,  true ] } } );

删除带有 _id : 1 的文档。

请注意 created 字段有 date/time 毫秒。在我测试的时候, date/time 和相应的毫秒: ISODate("2019-11-28T03:20:03.835Z")1574911160308.