mongodb

MongoDB: How to define a schema?


So I have an application that uses MongoDB as a database. The application makes use of a few collections.

When and how should I go about defining the "schema" of the database which includes setting up all the collections as well as indexes needed?

AFAIK, you are unable to define empty collections in MongoDB (correct me if I am wrong, if I can do this it will basically answer this question). Should I insert a dummy value for each collection and use that to setup all my indexes?

What is the best practice for this?


Solution

  • You don't create collections in MongoDB.
    You just start using them immediately whether they “exist” or not.

    Now to defining the “schema”. As I said, you just start using a collection, so, if you need to ensure an index, just go ahead and do this. No collection creation. Any collection will effectively be created when you first modify it (creating an index counts).

    > db.no_such_collection.getIndices()
    [ ]
    > db.no_such_collection.ensureIndex({whatever: 1})
    > db.no_such_collection.getIndices()
    [
            {
                    "v" : 1,
                    "key" : {
                            "_id" : 1
                    },
                    "ns" : "test.no_such_collection",
                    "name" : "_id_"
            },
            {
                    "v" : 1,
                    "key" : {
                            "whatever" : 1
                    },
                    "ns" : "test.no_such_collection",
                    "name" : "whatever_1"
            }
    ]