Skip to main content

Import/Export Mongo Schema

Import and export mongodb schemas without copying all the data. It will extract the following meta data about a mongo database:

  • Collections
  • Indexes
  • Cap sizes
  • Schema validators

The primary use case is when you have developed an application that uses mongodb, and want to setup a new instance with the appopriate database layout. You can then provide a config.json file with your application and have this script setup the database for you without the need for extra ensureIndex calls!

This data will be stored in a json file for a database that looks something like this:

{
    "databases": {
        "test": {
            "location": {
                "indexes": [
                    {
                        "name": "_id_",
                        "keys": [
                            [
                                "_id",
                                1
                            ]
                        ]
                    },
                    {
                        "name": "pos_2dsphere",
                        "2dsphereIndexVersion": 3,
                        "keys": [
                            [
                                "pos",
                                "2dsphere"
                            ]
                        ]
                    },
                    {
                        "name": "device_1_timestamp_1",
                        "keys": [
                            [
                                "device",
                                1
                            ],
                            [
                                "timestamp",
                                1
                            ]
                        ]
                    }
                ],
                "options": {}
            },
            "users": {
                "indexes": [
                    {
                        "name": "_id_",
                        "keys": [
                            [
                                "_id",
                                1
                            ]
                        ]
                    },
                    {
                        "unique": true,
                        "name": "username_idx",
                        "keys": [
                            [
                                "username",
                                1
                            ]
                        ]
                    }
                ],
                "options": {
                    "validator": {
                        "$jsonSchema": {
                            "bsonType": "object",
                            "required": [
                                "username",
                                "password",
                                "level"
                            ],
                            "properties": {
                                "username": {
                                    "bsonType": "string",
                                    "description": "must be a string and is required"
                                },
                                "level": {
                                    "bsonType": "string",
                                    "enum": [
                                        "user",
                                        "admin",
                                        "moderator"
                                    ],
                                    "description": "must be a string"
                                },
                                "password": {
                                    "bsonType": "string",
                                    "description": "must be a bcrypt password",
                                    "pattern": "^\\$2b\\$\\d{1,2}\\$[A-Za-z0-9\\.\\/]{53}$"
                                }
                            }
                        }
                    },
                    "validationLevel": "strict",
                    "validationAction": "error"
                }
            },
            "capped": {
                "indexes": [
                    {
                        "name": "_id_",
                        "keys": [
                            [
                                "_id",
                                1
                            ]
                        ]
                    },
                    {
                        "unique": true,
                        "name": "key_1",
                        "keys": [
                            [
                                "key",
                                1
                            ]
                        ]
                    }
                ],
                "options": {
                    "capped": true,
                    "size": 64000,
                    "max": 5000,
                    "validator": {
                        "$jsonSchema": {
                            "bsonType": "object",
                            "description": "Simple key value store",
                            "required": [
                                "key",
                                "value"
                            ],
                            "properties": {
                                "key": {
                                    "bsonType": "string",
                                    "maxLength": 64.0,
                                    "description": "the key value"
                                },
                                "value": {
                                    "bsonType": "string",
                                    "description": "the associated value"
                                }
                            }
                        }
                    },
                    "validationLevel": "strict",
                    "validationAction": "error"
                }
            }
        }
    },
    "exported": "2018-07-18T17:12:43.460992"
}

Installation

pip install MongoSchemaImportExport

Usage

Make sure the user you are using to import/export has the appropriate privileges, they'll probably need to have the root role or dbOwner on the source and destination. To export your data run:

mongo-schema-export.py --uri mongodb://user:password@database.host1.com:27017/admin --databases test2,testIgnore

To import your schema run as bellow. Use --delete-col to delete collections before creating them (WARNING: this will delete your data, you cannot change an existing collection into a capped one, although, you can set a validator after creation):

mongo-schema-import.py --uri mongodb://user:password@database.host2.com:27017/admin --databases db_1,db_2 --verbose --delete-col

You will get an output like this:

Skipping: testIgnore
Creating database: test2
	Dropping collection location
	Creating collection: location
		Options {}
		Creating index: {'name': '_id_', 'keys': [['_id', 1]]}
		Creating index: {'name': 'pos_2dsphere', '2dsphereIndexVersion': 3, 'keys': [['pos', '2dsphere']]}
		Creating index: {'name': 'device_1_timestamp_1', 'keys': [['device', 1], ['timestamp', 1]]}
	Dropping collection users
	Creating collection: users
		Options {'validator': {'$jsonSchema': {'bsonType': 'object', 'required': ['username', 'password', 'level'], 'properties': {'username': {'bsonType': 'string', 'description': 'must be a string and is required'}, 'level': {'bsonType': 'string', 'enum': ['user', 'admin', 'moderator'], 'description': 'must be a string'}, 'password': {'bsonType': 'string', 'description': 'must be a bcrypt password', 'pattern': '^\\$2b\\$\\d{1,2}\\$[A-Za-z0-9\\.\\/]{53}$'}}}}, 'validationLevel': 'strict', 'validationAction': 'error'}
		Creating index: {'name': '_id_', 'keys': [['_id', 1]]}
		Creating index: {'unique': True, 'name': 'username_idx', 'keys': [['username', 1]]}
	Dropping collection capped
	Creating collection: capped
		Options {'capped': True, 'size': 64000, 'max': 5000, 'validator': {'$jsonSchema': {'bsonType': 'object', 'description': 'Simple key value store', 'required': ['key', 'value'], 'properties': {'key': {'bsonType': 'string', 'maxLength': 64.0, 'description': 'the key value'}, 'value': {'bsonType': 'string', 'description': 'the associated value'}}}}, 'validationLevel': 'strict', 'validationAction': 'error'}
		Creating index: {'name': '_id_', 'keys': [['_id', 1]]}
		Creating index: {'unique': True, 'name': 'key_1', 'keys': [['key', 1]]}

If you get permission errors, make sure your user has the right roles to read and write databases and collections.

Metadata

Release files for MongoSchemaImportExport 0.2.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for MongoSchemaImportExport 0.2.4
File Size Uploaded Provenance
MongoSchemaImportExport-0.2.4.tar.gz 5.3 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for MongoSchemaImportExport 0.2.4
File Interpreter ABI Platform
MongoSchemaImportExport-0.2.4-py3-none-any.whl Python 3 none any Details

Total release size: 14.4 kB

Release files / MongoSchemaImportExport-0.2.4.tar.gz

Download URL MongoSchemaImportExport-0.2.4.tar.gz
Size 5.3 kB
Tags Source
SHA-256 checksum
How to use checksums
35ab0fe5d096d3e69dc93d9fc79cdf2a9f2b61a78587b8b0b199a56ac2e5ea96
BLAKE2b-256 checksum
How to use checksums
a78f91d96fee63dd0d8b016572042b905df7acb2ea1004834906f4743c87a6db
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.12.1 pkginfo/1.4.2 requests/2.18.4 setuptools/40.0.0 requests-toolbelt/0.8.0 tqdm/4.23.0 CPython/3.6.4

Release files / MongoSchemaImportExport-0.2.4-py3-none-any.whl

Download URL MongoSchemaImportExport-0.2.4-py3-none-any.whl
Size 9.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
400b98eb8c12b85db1eb824ba429a59d205edc594fca08f25846e45c1ae7a5a1
BLAKE2b-256 checksum
How to use checksums
ba9c4eb67b50ab910f9ee7689546020000040838a35f65078c478f1f8830bc5e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.12.1 pkginfo/1.4.2 requests/2.18.4 setuptools/40.0.0 requests-toolbelt/0.8.0 tqdm/4.23.0 CPython/3.6.4

Security for MongoSchemaImportExport 0.2.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page