Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pymongo .eval() vs. Mongo shell --eval

What is the equivalent of this command in pymongo using .eval()?

mongo localhost/mydb --quiet --eval "printjson(db.getCollectionNames())"

Because this doesn't seem to work and returns nothing:

from pymongo import MongoClient    
client = MongoClient("mongodb://localhost")
db = client.mydb     
myjs = "printjson(db.getCollectionNames())"
print db.eval(myjs)

Yes, I understand how db.collection_names() works, I specifically need to understand how to correctly pass javascript with printjson() to pymongo.eval()` and get the same response back as I would from the original shell command.

like image 386
perdurabo93 Avatar asked Oct 25 '25 02:10

perdurabo93


1 Answers

This is because you are using printjson() which is not a JavaScript function. Use return instead.

In [6]: c = Code("function(){return db.getCollectionNames()}")

In [7]: db.eval(c)
Out[7]: 
['bar',
 'baz',
 'col',
 'collection',
 'demo',
 'first_use',
 'sCriteria',
 'spam',
 'system.indexes',
 'test',
 'v']
like image 193
styvane Avatar answered Oct 27 '25 00:10

styvane