1

I want to run the same query for all databases

`

for example

import pymongo

db = pymongo.MongoClient("localhost")

db["*"]["test"].find()

or

import pymongo

db = pymongo.MongoClient("localhost")

db["db1","db2","db3"]["test"].find()

To put it bluntly, how to run this logic in mongodb

import pymongo

db = pymongo.MongoClient("localhost")

db_names = db.list_database_names()

for x  in db_names:
   db[x]["test"].find()
8
  • 1
    Does this answer your question? how to get list of all databases in a mongo instance using pymongo Commented Nov 28, 2022 at 21:36
  • No , i need run query for all databases Commented Nov 28, 2022 at 21:38
  • I'm pretty sure that you have to issue one query per database. What are you trying to do here? The .find() queries in your example are empty, are you trying to export data or are you looking to find a value and don't know what collection it is in? Commented Nov 28, 2022 at 21:41
  • @user20042973 Each clone has the same documentation name and databases are created by users. Frankly, I need to send the same query to all databases, I can do this with a simple code with python, but I want to send it as a mongo db query. Commented Nov 28, 2022 at 21:44
  • I don't think it is possible to do that. Every query is specific to a collection. Via aggregation (eg $unionWith) it is possible to query multiple collections within the same database at once, but nothing across databases. Commented Nov 28, 2022 at 21:45

1 Answer 1

1

There are no commands to run the same query on multiple databases in a single command.

You can get the list of databases and repeat the same command by iterating the list_database_names() method which you can run against the MongoClient instance, e.g.

import pymongo

client = pymongo.MongoClient()
collection = 'mycollection'


for x in client.list_database_names():
    print(client[x][collection].count_documents({}))
Sign up to request clarification or add additional context in comments.

2 Comments

Python is slow here if there are billions of databases.
If you have billions of databases, the speed of python is the least of your problems.

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.