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

上下文:我正在创建一个用户可以在其中创建帐户的网站。然后,他们必须通过打开验证电子邮件来验证其帐户。我正在使用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为我做逻辑/过滤器?

SCORPIOYUKI 回答:如何在Mongodb过滤器中使用比较

mongo shell 中工作,让我们获取以下三个输入文档:

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

为查询创建过滤器以选择具有以下条件的文档:

  

Date.now()>创建+ 1000 * 60 * 60 * 24 && typeof(notValid)==   “字符串”

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 ] } } )返回文档:

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

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

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

使用_id : 1删除文档。

请注意,created字段的日期/时间为毫秒。在我测试时,日期/时间和相应的毫秒数:ISODate("2019-11-28T03:20:03.835Z")1574911160308

本文链接:https://www.f2er.com/3019595.html

大家都在问