Home:ALL Converter>Retrieving all documents of all collections from a database in MongoDB with PyMongo

Retrieving all documents of all collections from a database in MongoDB with PyMongo

Ask Time:2017-02-22T20:43:36         Author:Hendrik

Json Formatter

I have a MongodDB database (mydbase) with different collections in it (coll1, coll2, coll3). I want to collect all documents of all collections in a structure of list (=database) of lists (=collections) of dicts (documents) with PyMongo. I tried the following:

[list(db.coll.find({})) for coll in db.collection_names()]

but it returns a list of empty lists. Which is kind of a weird, because if I query only one collection in a similar way:

list(db.coll1.find({}))

that gives a populated list as hoped for. What is the problem here?

Author:Hendrik,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/42391843/retrieving-all-documents-of-all-collections-from-a-database-in-mongodb-with-pymo
thanasisp :

test = [ list(db[coll].find({})) for coll in db.collection_names() ]\n\n\ncoll is a variable, so we need to use db[coll] instead of db.coll\n\nfor example, for a db with a collection named 'knights'\n\ndb.knights.find_one({}) # correctly from 'knights'\nn = 'knights'\ndb.n.find_one({}) # get one document from 'n'\ndb[n].find_one({}) # correctly from 'knights'\ndb['n'].find_one({}) # from 'n' again\n",
2017-02-22T13:09:46
yy