Created
June 6, 2025 14:19
-
-
Save samukasmk/7dc0f521a834ea2fb30b734b02ef33fd to your computer and use it in GitHub Desktop.
Python tool to execute MongoDB query filter by command line
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
import json | |
import argparse | |
from pymongo import MongoClient | |
parser = argparse.ArgumentParser( | |
prog='mongodb_query_filter.py', | |
description='Execute mongodb queries' | |
) | |
parser.add_argument('-u', '--url', required=True, help='MongoDB URL') | |
parser.add_argument('-s', '--schema', required=True, help='MongoDB Schema') | |
parser.add_argument('-c', '--collection', required=True, help='MongoDB Collection') | |
parser.add_argument('-f', '--filter', help='MongoDB Filter', default='{}') | |
parser.add_argument('-p', '--projection', help='MongoDB Projection', default='{"id": 1, "name": 1}') | |
args = parser.parse_args() | |
# convert json to dict | |
query = json.loads(args.filter) | |
projection = json.loads(args.projection) | |
# connect in mongodb | |
client = MongoClient(args.url) | |
db = client[args.schema] | |
collection = db[args.collection] | |
# execute query | |
results = collection.find(query, projection) | |
# print query results | |
for doc in results: | |
print('id:', doc["_id"], '-', 'name:', doc["name"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment