Inserting a Document into a Collection

Once you have a handle to your database, you can begin inserting data. Let us imagine we have a collection called “users”, containing all the users of our game. Each user has a username, a first name, surname, date of birth, email address and a score. We want to add a new user:

""" An example of how to insert a document """
import sys

from datetime import datetime
from pymongo import Connection
from pymongo.errors import ConnectionFailure

def main():
    try:
        c = Connection(host="localhost", port=27017)
    except ConnectionFailure, e:
        sys.stderr.write("Could not connect to MongoDB: %s" % e)
        sys.exit(1)
    dbh = c["mydb"]
    assert dbh.connection == c
    user_doc = {
        "username" : "janedoe",
        "firstname" : "Jane",
        "surname" : "Doe",
        "dateofbirth" : datetime(1974, 4, 12),
        "email" : "janedoe74@example.com",
        "score" : 0
    }

    dbh.users.insert(user_doc, safe=True)
    print "Successfully inserted document: %s" % user_doc

if __name__ == "__main__":
    main()

Note that we don’t have to tell MongoDB to create our collection “users” before we insert to it. Collections are created lazily in MongoDB, whenever you access them. This has the advantage of being very lightweight, but can occasionally cause problems due to typos. These can be hard to track down unless you have good test coverage. For example, imagine you accidentally typed:

# dbh.usrs is a typo, we mean dbh.users!  Unlike an RDBMS, MongoDB won't
# protect you from this class of mistake.
dbh.usrs.insert(user_doc)

The code would ...

Get MongoDB and Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.