0

I am looking for way to execute string mongodb queries such as :

 var q = 'db.collection("restaurants").find({   "address.coord": {     $lt: -95.754168   } })';
 this.db.eval('function(){ return ' + q + '.toArray(); }', function(err, res){
             console.log("the result is", res); 
 });o 

I understand from official MongoDb Documentation that this used to be possible earlier but it's not now.

Is there another way of achieving this?

I understand that I could store query condition and projections in variables and pass it on as dynamic entities. But is it also possible to go all the way dynamic and execute string queries fetched from a database on the fly?

Can I do without such dynamic nature? May be, may be not. But I want to know all my options.

3
  • Aggregation pipeline, $expr, map/reduce. Commented Aug 10, 2020 at 17:09
  • In your example eval appears to be completely unnecessary. Commented Aug 10, 2020 at 17:10
  • @D.SM its an example Commented Aug 10, 2020 at 17:50

1 Answer 1

1

But is it also possible to go all the way dynamic and execute string queries fetched from a database on the fly?

No.

The server is moving in the opposite direction and is expanding MQL and aggregation pipeline with additional (structured) functionality.

eval is meant to be replaced with the structured query options like the aggregation pipeline and $expr. Many of the aggregation pipeline stages and operators support variables.

If the aggregation pipeline isn't flexible enough, map/reduce continues to remain available as the closest direct alternative to eval.

Sign up to request clarification or add additional context in comments.

2 Comments

Aggregation framework looks promising. I thought it is only meant for queries such the ones that have "group by" clause. But turns out it could also be used for simple select queries as well. Thank you for bringing this to my notice. Also I came across something called db.command() which is kind of like eval but not exactly.
I would say db.command is nothing like eval at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.