vishesh
vishesh

Reputation: 2045

MongoDB parameterised query

In my nodejs code, I'm using mongoose to run mongo queries.

I'm exploring ways to completely externalise the queries from code. Ideally, the queries would just be json objects stored in queries.json. However, I'm not sure how to handle parameter in the query.

For example, I need to pass a certain id, I now need to create a javascript function that takes the id and constructs the query object by baking the id into it.

While in SQL world, there exist prepared statements, I believe MongoDB works different. But it would be just much cleaner to have queries as JSON, as then I can just run these queries in mongo shell, passing params together, rather than using a javascript file to do the job

Upvotes: 0

Views: 573

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59456

A Mongo query is a JSON object. Parameters like in SQL prepared statements are not possible. But you can do it for example like this:

var id = "foo";
var pipeline = [
   {$match: {name: id}},
   {$project: {name: 1, mail: 1}}
];
pipeline.push({$limit: 3});

db.collection.aggregate(pipeline);

// Use a different value for match:
pipeline[0]['$match'].name = "bar";
db.collection.aggregate(pipeline);

Upvotes: 1

Related Questions