Last active
August 29, 2015 14:06
-
-
Save jsoucheiron/51ff8de48b3fe6dc9853 to your computer and use it in GitHub Desktop.
Get random mongoDB document
This file contains 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
import argparse | |
import json | |
import random | |
from pymongo import MongoClient | |
def get_random_document(host, port, database, collection, filter, fields): | |
c = MongoClient( | |
host=host, | |
port=port | |
) | |
col = c[database][collection] | |
count = col.find(filter).count() | |
cursor = col.find(filter, fields, skip=random.randint(0, count - 1), limit=1) | |
doc = cursor[0] | |
return doc | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description='Get a random mongo document') | |
parser.add_argument('--host', help='Mongodb server address', default='127.0.0.1') | |
parser.add_argument('--port', help='Mongodb server port', default=27017) | |
parser.add_argument('--filter', help='Filter', default='{}') | |
parser.add_argument('--fields', help='Fields', default=None) | |
parser.add_argument('database', help='Mongodb database') | |
parser.add_argument('collection', help='Mongodb collection') | |
parsed_args = parser.parse_args() | |
if parsed_args.fields is None: | |
fields = None | |
else: | |
fields = json.loads(parsed_args.fields) | |
json_doc = get_random_document( | |
parsed_args.host, | |
parsed_args.port, | |
parsed_args.database, | |
parsed_args.collection, | |
json.loads(parsed_args.filter), | |
fields | |
) | |
print str(json_doc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment