MongoDB functions with date query

How does one write a JSON with Data Queries? I am building a mongodb function to accept HTTP request and parse query. I’ve tried new Date(“2016-10-11T00:00:00Z”) and ISO date function. I always end up with JSON parse errors as it can’t accept functions. How can we write a dynamic query string which can be sent in requestbody of http call? Thaks.

	"query": {"account.companyName":"Groups","_createdAt":{"$gte":ISODate("2016-10-11T00:00:00Z")}},
	"projection": {
		"crn": 1,
		"state": 1
t= JSON.parse(body);
 var res=  collection.find(t.query,t.projection,function(err, cursor){

Hi :wave: @SLOKA,

Welcome to the MongoDB Community forums :sparkles:

Just to clarify when we use JSON.parse() on the ISODate

– it gets converted to

Wed Oct 12 2022 11:04:45

However, I recommend avoiding freeform queries like this on API endpoints. Instead of allowing the body of the endpoint to be a freeform JSON document that is sent directly to the server, let the endpoint accept only date values as the body.

Consider the security aspect of the database, let’s say your body is empty, then it can clone your entire collection.

Thus, we can write the above query considering the above endpoints:

const { date } = req.body;
const res = await collections.aggregate([
    $match: {
      "account.companyName": "Groups",
      _createdAt: {
        $gte: date.toISOString()
    $project: {
      "crn": 1,
      "state": 1

I hope it helps!

Let us know if you have any further questions.


Thanks Kesav. I am working on the some basic adapter like function query that can be changed at run time by the end user with the selection of the fields. So, I want to build the query outside of Mongodb.