简体   繁体   English

MongoDB 查找带有日期比较的查询(NodeJs)

[英]MongoDB find Query with date comparison ( NodeJs)

I am new to MongoDB and I've been trying to get scheduled control messages in my collection, for example one CM is scheduled for today 15h and now is 15h, by logic i should compare the date using $lte (less than or equal)我是 MongoDB 的新手,我一直在尝试在我的集合中获取预定的控制消息,例如,一个 CM 计划在今天 15 小时,现在是 15 小时,按逻辑我应该使用$lte比较日期(小于或等于)

the query:查询:

/*Getting the Date (my schedule is only with hours and minutes)*/

var nowDate = new Date();
nowDate.setSeconds(0);
nowDate.setMilliseconds(0);


/*The Query*/ 
dbo.collection("control_message").find(
            { "status": { $in: [3,4] }},
            {
                $or: [ { schedule:{$exists: false}},{schedule:{date:{ $lte :nowDate}}}]
            }

        )

why i am asking this?我为什么要问这个?

because there are CMs (control messages) scheduled for 17h even though now it's 15h and the query is getting them.因为有 CM(控制消息)安排在 17 小时,即使现在是 15 小时并且查询正在获取它们。

I printed the nowDate to verify: 2020-12-13T15:33:00.000Z我打印了nowDate来验证: 2020-12-13T15:33:00.000Z

The scheduled time is: 2020-12-13T17:00:00.000Z预定时间为: 2020-12-13T17:00:00.000Z

same query on MySQL (works): MySQL 上的相同查询(有效):

SELECT id_control_message AS control_message_id , app_id, title, body, channel,url_push, img_push, silent, status 
                            FROM control_message 
                            WHERE (status = 3 OR status = 4) 
                            AND (schedule IS NULL OR schedule <= NOW())

Control Message Document example:控制消息文档示例:

{
_id: '5fd3e48eac3f2b3ede0a6a52',
sent_in: {
  date: 2020-12-11T21:28:46.760Z,
  short_date: 2020-12-11T21:28:46.760Z
},
sender_id: 266,
app_id: 190,
message_type_id: 1,
title: '',
body: '',
schedule: {
  date: 2020-12-13T17:00:00.000Z,
  short_date: 2020-12-13T17:00:00.000Z
},
ip: '172.31.55.83',
status: 4
}

Thanks to turivishal , I've noticed in the playground example he sent me that the logic of the my query was wrong since i didn't add the $and operator,it wasn't returning the right results.感谢turivishal ,我在他发给我的操场示例中注意到我的查询逻辑是错误的,因为我没有添加$and运算符,它没有返回正确的结果。 Not only that, but specifying which date to compare with "schedule.date" instead of using just "schedule" was the correct way to compare (in my case)不仅如此,而且指定与"schedule.date"比较的日期而不是仅使用"schedule"是比较的正确方法(在我的情况下)

The corrected query:更正后的查询:

dbo.collection("control_message").find({
        $and: [
            {"status": { $in: [3,4] }},
            {
                $or: [ { schedule:{$exists: false}},{"schedule.date":{ $lte :nowDate}}]
            }

         ]
          })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM