2

Is there a way in pymongo to use a string to execute a query instead of a dictionary? I would like to be able to use exactly the same syntax as on MongoDB shell from python/pymongo. Is that possible?

3
  • What kind of syntax are you looking for? You could probably define a helper function that does this for you. It's common for me, for example, to create a function like def find(s): return mongo.db.col.findOne({"_id": s}) Commented Jan 19, 2013 at 22:34
  • yes but that's not what I was looking for. The poc i'm working is needs to execute whatever query provided by a user. I want to leave all the real work up to the mongodb server itself. Commented Jan 20, 2013 at 10:07
  • That does not sound like a very good idea. You understand a crafty user would be able to read and write whatever they want to your database? Commented Jan 20, 2013 at 22:14

2 Answers 2

1

MongoDB shell is full-featured javascript console/interpreter with some bindings to message with a mongodb server. In contrast PyMongo lacks embedded javascript interpreter or even javascript parser so you could not execute MongoDB shell queries as-is.

Note that mongo shell queries are not json documents as they are able to contain some functions and some object constructors such as {value: 2+2}.

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

1 Comment

Yes, you're right that puts everything into context. Then what I'm looking for is a way to execute javascript code through pymongo. I'll have a look at mjhm's proposal of eval()
1

The eval() function might be what you're looking for. Note that it executes the JS code on the db server -- NOT in a Mongo shell on some client. Therefore it comes with lots of warnings, and I would strongly advise against using it in a serious production situation. See the Mongo db.eval docs for details and examples.

2 Comments

That might indeed be what I'm looking for. I'm going to do some testing and let you know the outcome.
That wont be efficient - I'd recommend using the idiomatic python that pymongo gives you. It will be more efficient and is native python, which maps closely to the native shell.

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.