Home > Net >  Get data from JSON using query parameters
Get data from JSON using query parameters

Time:03-08

I have to make an API whose endpoint will be like day=1&time=1000 and by using these query parameters I have to write a mongo query, JSON will be like

       "_id" : ObjectId("62257ddd76b35400010e7015"),
       "applyOffersOn" : [
               {
                       "day" : 1,
                       "startTime" : NumberLong("1646625639561"),
                       "endTime" : NumberLong("1646631039561"),
                       "startTimeFormat" : NumberLong(930),
                       "endTimeFormat" : NumberLong(1100)
               },
               {
                       "day" : 2,
                       "startTime" : NumberLong("1646625639561"),
                       "endTime" : NumberLong("1646631039561"),
                       "startTimeFormat" : NumberLong(930),
                       "endTimeFormat" : NumberLong(1100)
               },
               {
                       "day" : 3,
                       "startTime" : NumberLong("1646625639561"),
                       "endTime" : NumberLong("1646631039561"),
                       "startTimeFormat" : NumberLong(1930),
                       "endTimeFormat" : NumberLong(2100)
               }
       ],
     
}```

the query should be like I have to first check for a particular object using objectId then finding the object, check for the day is present as 1 and then check for the time that it will be between  
startTimeFormat and endTimeFormat if all these conditions satisfy then return the whole object 

I have written the query but it either works for the day or for a time but it should work like it check for both condition 



CodePudding user response:

I think this will help ,

##elemMatch - it will loop you through all elements of array.

const answer = <your model schema>.findById(req.params.id).find({applyOffersOn:{$elemMatch:{day:<your day from query> } }}).find({applyOffersOn:{$elemMatch : {startTimeFormat: {$lte:<your time from query> },endTimeFormat:{$gte:<your time from query>} }}})

  • Related