Regarding Complex Queries

225 views
Skip to first unread message

Michael De Marco

unread,
Mar 15, 2017, 10:40:29 PM3/15/17
to mongodb-user
Building queries in node.js is tedious. You can't pass mongo a string as in the following below with single quotes at the beginning and end. You can't parse the object.
My question is what is the recommended approach to building complex queries without  having to build a json object on the fly. I want something akin to a stored procedure in SQL server where I can pass parameters and plug them and run. What is available? Any other approach?

db.tickets.find('{ "started": { "$gte": new Date("2016-01-01T00:00:00.000Z"), "$lt": new Date("2016-01-02T00:00:00.000Z")  }}')

Wan Bachtiar

unread,
Mar 30, 2017, 1:05:22 AM3/30/17
to mongodb-user

You can’t pass mongo a string as in the following below with single quotes at the beginning and end. You can’t parse the object.

Hi Michael,

The MongoDB Node.JS driver find() method expects not a string, but a query object (JSON). This means that you would need to convert the string into JSON first before passing it through.

Usually a pure JSON string can be parsed utilising JSON.parse(). However, your example query string contains JavaScript statement i.e. new Date() which can’t be handled by JSON.parse().

I’d recommend to change the format of your string to be in MongoDB extended JSON strict mode. For example, your query string would be:

'{ "started": { "$gte": {"$date": "2016-01-01T00:00:00.000Z"}, "$lt": {"$date":"2016-01-02T00:00:00.000Z"}}}'

You can then utilise npm module mongodb-extended-json to parse this into JSON. for example:

var extJSON = require("mongodb-extended-json");
var query = extJSON.parse('{ "started": { "$gte": {"$date": "2016-01-01T00:00:00.000Z"}, "$lt": {"$date":"2016-01-02T00:00:00.000Z"}}}');

db.collection.find(query);

See also Node.JS driver quick-start for more information.

I want something akin to a stored procedure in SQL server where I can pass parameters and plug them and run. What is available? Any other approach?

You can also write a JavaScript function that you could call in your Node.Js script (client side). Invoke the function and pass parameters to it, which wraps the query.

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages