简体   繁体   中英

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)

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.

I printed the nowDate to verify: 2020-12-13T15:33:00.000Z

The scheduled time is: 2020-12-13T17:00:00.000Z

same query on MySQL (works):

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. 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)

The corrected query:

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

         ]
          })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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