Login

MongoDB data dump

Author:
jose_lpa
Posted:
January 3, 2013
Language:
Python
Version:
1.4
Tags:
dump fixtures mongodb
Score:
0 (after 0 ratings)

This Django management command just dumps data from a given MongoDB collection into a JSON file.

To get it working, just create a MONGODB_NAME variable in settings, holding the name of your Mongo database. This can be edited to fit more your needs. The snippet requires Pymongo, since it uses its bson module and the MongoClient.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings

from optparse import make_option
from bson.json_util import dumps
from pymongo import MongoClient


class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--filename', '-f',
                    dest='filename',
                    help='Sets the name of the dumped data file.'),
    )

    help = "Dumps data (in JSON) from the MongoDB database.\n\n" \
           "Usage: manage.py mongo_dump MODEL"

    def handle(self, *args, **options):
        if not args:
            raise CommandError('Please specify a model in Mongo database to '
                               'dump its existent data.')

        filename = options.get('filename')

        connection = MongoClient()
        db = connection[settings.MONGODB_NAME]

        collection = db[args[0]]

        if not filename:
            filename = args[0] + '.json'

        with open(filename, 'w') as f:
            for doc in collection.find():
                f.write(dumps(doc) + '\n')

More like this

  1. Quick script to convert json data to csv by stephenemslie 5 years, 4 months ago
  2. ajax protocol for data by limodou 8 years, 6 months ago
  3. MongoDB data load by jose_lpa 2 years, 8 months ago
  4. JSON fixtures of Intl. country codes & dial-codes by dibau_naum_h 5 years ago
  5. dump_app_data: dumps application data to the application's fixtures directory by wolever 4 years, 1 month ago

Comments

Please login first before commenting.