Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find names of all collections using PyMongo?

Tags:

python

pymongo

How to find names of all collections using PyMongo and find all fields in chosen collection ? I have name of database and name of chosen collection. (Scenario : user input name of database, need to find all collections and show in dropdown list, when user click on one item need to find all fields in that collection)

like image 749
Damir Avatar asked Mar 21 '12 13:03

Damir


People also ask

How do I list collections in MongoDB?

To list all collections in Mongo shell, you can use the function getCollectionNames().

How do I find a document in PyMongo?

The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn't use any query it returns the first document of the collection.


2 Answers

To find the collections, you can use collection_names() - https://pymongo.readthedocs.io/en/stable/api/pymongo/database.html#pymongo.database.Database.collection_names

Update:

The collection_names is deprecated from 3.7 onwards and been replaced by list_collection_names() - https://pymongo.readthedocs.io/en/stable/api/pymongo/database.html#pymongo.database.Database.list_collection_names

like image 168
Dogbert Avatar answered Sep 19 '22 05:09

Dogbert


This is very simple. e.g.

import pymongo import json  if __name__ == '__main__':     client = pymongo.MongoClient("localhost", 27017, maxPoolSize=50)     d = dict((db, [collection for collection in client[db].collection_names()])              for db in client.database_names())     print json.dumps(d) 

result -> {"database1":["collection1","collection2"...], "database2": [...], ...}, like:

{"test": ["score", "test4", "test5", "test6", "test3", "test7", "user", "test2", "test8"],  "testdb": ["test5", "test8", "test2", "test9", "test3", "test4", "test6", "test"],  "local": ["startup_log"],  "stackoverflow": ["questions"]} 
like image 35
Little Roys Avatar answered Sep 22 '22 05:09

Little Roys