Hands-on MongoDB :: Part-2


Bhaskar S 03/14/2014


Introduction

In Part-1, we got our hands dirty in MongoDB by using the mongo command-line interface.

In this part, we will explore the same operations on MongoDB through programming using languages Python and Java.

Hands-on with Python MongoDB Driver

The following is the Python program called Mongo-1.py that performs all the operations we executed through the command-line interface in Part-1:

Mongo-1.py
import pymongo

# Open connection to MongoDB @ localhost:27017

try:
    client = pymongo.MongoClient('localhost', 27017);
    print("Connected to MongoDB @ localhost:27017")
except pymongo.errors.ConnectionFailure, e:
    print("ERROR: Could not connect to MongoDB @ localhost:27017: %s" % e)

# Setup the db variable to point to the database mydb

db = client["mydb"]

# Setup the contacts variable to point to the collection contacts

contacts = db["contacts"]

# Display all the collections in the database mydb

print("List of collections: %s" % db.collection_names())

# Insert a document into the collection contacts

contacts.insert({ "first": "Bill", "last": "Gates", "email": "bill.gates@microsoft.com", "mobile": "123 456 7890" })

# Display all the collections in the database mydb

print("List of collections: %s" % db.collection_names())

# Display the number of documents in the collection contacts

print("Number of documents in contacts: %s" % contacts.count())

# Query and display all the documents in the collection contacts

cursor = contacts.find()
for doc in cursor:
    print(doc)

# Insert four more documents into the collection contacts

contacts.insert({ "first": "James", "last": "Gosling", "email": "jgosling@oracle.com", "mobile": "234 567 8901" })
contacts.insert({ "first": "Larry", "last": "Wall", "email": "larryw@perl.org" })
contacts.insert({ "first": "Guido", "middle": "van", "last": "Rossum",
                  "email": "gvr@python.org", "mobile": "345 678 9012" })
contacts.insert({ "first": "Anders", "last": "Hejlsberg", "email": "anders@microsoft.com", "mobile": "456 789 0123" })

# Query and display all the documents in the collection contacts

print("Documents in contacts:")
cursor = contacts.find()
for doc in cursor:
    print(doc)

# Query and display the document for first = "Larry" from the collection contacts

print("Document for Larry:")
print(contacts.find_one({ "first": "Larry" }))

# Query and display the document for first = "Bill" and last = "Gates" from the collection contacts

print("Document for Bill Gates:")
print(contacts.find_one({ "first": "Bill", "last": "Gates" }))

# Query and display only first and last for all the documents in the collection contacts

print("First and Last name(s) in contacts:")
cursor = contacts.find({}, { "first": 1, "last": 1 })
for doc in cursor:
    print(doc)

# Query and display only first and last (without _id) for all the documents in the collection contacts

print("First and Last name(s) [without _id] in contacts:")
cursor = contacts.find({}, { "first": 1, "last": 1, "_id": 0 })
for doc in cursor:
    print(doc)

# Query and return the document for first = "Larry" from the collection contacts

doc = contacts.find_one({ "first": "Larry" })
print("first = %s, last = %s" % (doc["first"], doc["last"]))

# Query and display only first and last (without _id) for 3 documents in the collection contacts

print("First and Last name(s) [without _id with limit 3] in contacts:")
cursor = contacts.find({}, { "first": 1, "last": 1, "_id": 0 }).limit(3)
for doc in cursor:
    print(doc)

# Update the document for first = "Larry" in the collection contacts

contacts.update({ "first": "Larry" }, { "mobile": "987 654 3210" })

# Query and display the document for first = "Larry" from the collection contacts

print("Document for Larry [after update]:")
doc = contacts.find_one({ "first": "Larry" })
if (doc):
    print(doc)

# Query and display the document for mobile = "987 654 3210" from the collection contacts

print("Document for Larry [after update using mobile]:")
print(contacts.find_one({ "mobile": "987 654 3210" }))

# Update the document for mobile = "987 654 3210" (to restore Larry) in the collection contacts

contacts.update({ "mobile": "987 654 3210" }, { "first": "Larry",
                                                "last": "Wall",
                                                "email": "larryw@perl.org",
                                                "mobile": "987 654 3210" })

# Query and display the document for first = "Larry" from the collection contacts

print("Document for Larry [after update fix]:")
print(contacts.find_one({ "first": "Larry" }))

# Delete the document for first = "James" from the collection contacts

contacts.remove({ "first": "James" })

# Query and display all the documents in the collection contacts

print("Documents in contacts [after removing James]:")
cursor = contacts.find()
for doc in cursor:
    print(doc)

# Delete all the remaining documents for the collection contacts

contacts.remove()

# Display the number of documents in the collection contacts

print("Number of documents in contacts [after remove all]: %s" % contacts.count())

# Drop the collection contacts

contacts.drop()

# Display all the collections in the database mydb

print("List of collections: %s" % db.collection_names())

# Close the database connection

client.close()

print("Done !!!")

Let us try to understand the source code from Mongo-1.py above:

Executing Mongo-1.py will generate the following output:

Output.1

Connected to MongoDB @ localhost:27017
List of collections: [u'system.indexes']
List of collections: [u'system.indexes', u'contacts']
Number of documents in contacts: 1
{u'mobile': u'123 456 7890', u'_id': ObjectId('5324a0ef284cb12094322d0b'), u'last': u'Gates', u'email': u'bill.gates@microsoft.com', u'first': u'Bill'}
Documents in contacts:
{u'mobile': u'123 456 7890', u'_id': ObjectId('5324a0ef284cb12094322d0b'), u'last': u'Gates', u'email': u'bill.gates@microsoft.com', u'first': u'Bill'}
{u'mobile': u'234 567 8901', u'_id': ObjectId('5324a0ef284cb12094322d0c'), u'last': u'Gosling', u'email': u'jgosling@oracle.com', u'first': u'James'}
{u'_id': ObjectId('5324a0ef284cb12094322d0d'), u'last': u'Wall', u'email': u'larryw@perl.org', u'first': u'Larry'}
{u'last': u'Rossum', u'mobile': u'345 678 9012', u'middle': u'van', u'_id': ObjectId('5324a0ef284cb12094322d0e'), u'email': u'gvr@python.org', u'first': u'Guido'}
{u'mobile': u'456 789 0123', u'_id': ObjectId('5324a0ef284cb12094322d0f'), u'last': u'Hejlsberg', u'email': u'anders@microsoft.com', u'first': u'Anders'}
Document for Larry:
{u'_id': ObjectId('5324a0ef284cb12094322d0d'), u'last': u'Wall', u'email': u'larryw@perl.org', u'first': u'Larry'}
Document for Larry:
{u'mobile': u'123 456 7890', u'_id': ObjectId('5324a0ef284cb12094322d0b'), u'last': u'Gates', u'email': u'bill.gates@microsoft.com', u'first': u'Bill'}
First and Last name(s) in contacts:
{u'_id': ObjectId('5324a0ef284cb12094322d0b'), u'last': u'Gates', u'first': u'Bill'}
{u'_id': ObjectId('5324a0ef284cb12094322d0c'), u'last': u'Gosling', u'first': u'James'}
{u'_id': ObjectId('5324a0ef284cb12094322d0d'), u'last': u'Wall', u'first': u'Larry'}
{u'_id': ObjectId('5324a0ef284cb12094322d0e'), u'last': u'Rossum', u'first': u'Guido'}
{u'_id': ObjectId('5324a0ef284cb12094322d0f'), u'last': u'Hejlsberg', u'first': u'Anders'}
First and Last name(s) [without _id] in contacts:
{u'last': u'Gates', u'first': u'Bill'}
{u'last': u'Gosling', u'first': u'James'}
{u'last': u'Wall', u'first': u'Larry'}
{u'last': u'Rossum', u'first': u'Guido'}
{u'last': u'Hejlsberg', u'first': u'Anders'}
first = Larry, last = Wall
First and Last name(s) [without _id with limit 3] in contacts:
{u'last': u'Gates', u'first': u'Bill'}
{u'last': u'Gosling', u'first': u'James'}
{u'last': u'Wall', u'first': u'Larry'}
Document for Larry [after update]:
Document for Larry [after update using mobile]:
{u'mobile': u'987 654 3210', u'_id': ObjectId('5324a0ef284cb12094322d0d')}
Document for Larry [after update fix]:
{u'mobile': u'987 654 3210', u'_id': ObjectId('5324a0ef284cb12094322d0d'), u'last': u'Wall', u'email': u'larryw@perl.org', u'first': u'Larry'}
Documents in contacts [after removing James]:
{u'mobile': u'123 456 7890', u'_id': ObjectId('5324a0ef284cb12094322d0b'), u'last': u'Gates', u'email': u'bill.gates@microsoft.com', u'first': u'Bill'}
{u'last': u'Rossum', u'mobile': u'345 678 9012', u'middle': u'van', u'_id': ObjectId('5324a0ef284cb12094322d0e'), u'email': u'gvr@python.org', u'first': u'Guido'}
{u'mobile': u'456 789 0123', u'_id': ObjectId('5324a0ef284cb12094322d0f'), u'last': u'Hejlsberg', u'email': u'anders@microsoft.com', u'first': u'Anders'}
{u'mobile': u'987 654 3210', u'_id': ObjectId('5324a0ef284cb12094322d0d'), u'last': u'Wall', u'email': u'larryw@perl.org', u'first': u'Larry'}
Number of documents in contacts [after remove all]: 0
List of collections: [u'system.indexes']
Done !!!

The following is the Java program called Mongo_1.java that does exactly what the Python program Mongo-1.py above did:

Mongo_1.java
/*
 * 
 * Name:   Mongo_1
 * 
 * Author: Bhaskar S
 * 
 * Date:   03/15/2014
 * 
 */

package com.polarsparc.mongodb;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

public class Mongo_1 {
    public static void main(String[] args) {
        MongoClient client = null;
        
        try {
            // Open connection to MongoDB @ localhost:27017
            client = new MongoClient("localhost", 27017);
            
            System.out.printf("Connected to MongoDB @ localhost:27017\n");
            
            // Get reference to MongoDB database mydb
            DB db = client.getDB("mydb");
            
            // Get reference to the collection contacts
            DBCollection contacts = db.getCollection("contacts");
            
            // Display all the collections in the database mydb
            System.out.printf("List of collections: %s\n", db.getCollectionNames());
            
            // Insert a document into the collection contacts
            // { "first": "Bill", "last": "Gates", "email": "bill.gates@microsoft.com", "mobile": "123 456 7890" }
            BasicDBObject doc = new BasicDBObject();
            doc.put("first", "Bill");
            doc.put("last", "Gates");
            doc.put("email", "bill.gates@microsoft.com");
            doc.put("mobile", "123 456 7890");
            contacts.insert(doc);
            
            // Display all the collections in the database mydb
            System.out.printf("List of collections: %s\n", db.getCollectionNames());
            
            // Display the number of documents in the collection contacts
            System.out.printf("Number of documents in contacts: %d\n", contacts.count());
            
            // Query and display all the documents in the collection contacts
            DBCursor cursor = contacts.find();
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
            
            // Insert four more documents into the collection contacts
            // { "first": "James", "last": "Gosling", "email": "jgosling@oracle.com", "mobile": "234 567 8901" }
            // { "first": "Larry", "last": "Wall", "email": "larryw@perl.org" }
            // { "first": "Guido", "middle": "van", "last": "Rossum", "email": "gvr@python.org", "mobile": "345 678 9012" }
            // { "first": "Anders", "last": "Hejlsberg", "email": "anders@microsoft.com", "mobile": "456 789 0123" }
            BasicDBObject doc2 = new BasicDBObject();
            doc2.put("first", "James");
            doc2.put("last", "Gosling");
            doc2.put("email", "jgosling@oracle.com");
            doc2.put("mobile", "234 567 8901");
            BasicDBObject doc3 = new BasicDBObject();
            doc3.put("first", "Larry");
            doc3.put("last", "Wall");
            doc3.put("email", "larryw@perl.org");
            BasicDBObject doc4 = new BasicDBObject();
            doc4.put("first", "Guido");
            doc4.put("middle", "van");
            doc4.put("last", "Rossum");
            doc4.put("email", "gvr@python.org");
            doc4.put("mobile", "345 678 9012");
            BasicDBObject doc5 = new BasicDBObject();
            doc5.put("first", "Anders");
            doc5.put("last", "Hejlsberg");
            doc5.put("email", "anders@microsoft.com");
            doc5.put("mobile", "456 789 0123");
            contacts.insert(doc2);
            contacts.insert(doc3);
            contacts.insert(doc4);
            contacts.insert(doc5);
            
            // Query and display all the documents in the collection contacts
            System.out.printf("Documents in contacts:\n");
            cursor = contacts.find();
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
            
            // Query and display the document for first = "Larry" from the collection contacts
            System.out.printf("Document for Larry:\n");
            BasicDBObject criteria = new BasicDBObject();
            criteria.put("first", "Larry");
            System.out.println(contacts.findOne(criteria));
            
            // Query and display the document for first = "Bill" and last = "Gates" from the collection contacts
            System.out.printf("Document for Bill Gates:\n");
            criteria = new BasicDBObject();
            criteria.put("first", "Bill");
            criteria.put("last", "Gates");
            System.out.println(contacts.findOne(criteria));
            
            // Query and display only first and last for all the documents in the collection contacts
            BasicDBObject all = new BasicDBObject();
            BasicDBObject fields = new BasicDBObject();
            fields.put("first", 1);
            fields.put("last", 1);
            System.out.printf("First and Last name(s) in contacts:\n");
            cursor = contacts.find(all, fields);
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
            
            // Query and display only first and last (without _id) for all the documents in the collection contacts
            System.out.printf("First and Last name(s) [without _id] in contacts:\n");
            fields = new BasicDBObject();
            fields.put("first", 1);
            fields.put("last", 1);
            fields.put("_id", 0);
            cursor = contacts.find(all, fields);
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
            
            // Query and return the document for first = "Larry" from the collection contacts
            criteria = new BasicDBObject();
            criteria.put("first", "Larry");
            DBObject obj = contacts.findOne(criteria);
            System.out.printf("first = %s, last = %s\n", obj.get("first"), obj.get("last"));
            
            // Query and display only first and last (without _id) for 3 documents in the collection contacts
            System.out.printf("First and Last name(s) [without _id with limit 3] in contacts:\n");
            fields = new BasicDBObject();
            fields.put("first", 1);
            fields.put("last", 1);
            fields.put("_id", 0);
            cursor = contacts.find(all, fields).limit(3);
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
            
            // Update the document for first = "Larry" in the collection contacts
            // New document = { "mobile": "987 654 3210" }
            criteria = new BasicDBObject();
            criteria.put("first", "Larry");
            BasicDBObject newdoc = new BasicDBObject();
            newdoc.put("mobile", "987 654 3210");
            contacts.update(criteria, newdoc);
            
            // Query and display the document for first = "Larry" from the collection contacts
            System.out.printf("Document for Larry [after update]:\n");
            criteria = new BasicDBObject();
            criteria.put("first", "Larry");
            obj = contacts.findOne(criteria);
            if (obj != null) {
                System.out.println(obj);
            }
            
            // Query and display the document for mobile = "987 654 3210" from the collection contacts
            System.out.printf("Document for Larry [after update using mobile]:\n");
            criteria = new BasicDBObject();
            criteria.put("mobile", "987 654 3210");
            obj = contacts.findOne(criteria);
            if (obj != null) {
                System.out.println(obj);
            }
            
            // Update the document for mobile = "987 654 3210" (to restore Larry) in the collection contacts
            criteria = new BasicDBObject();
            criteria.put("mobile", "987 654 3210");
            doc3 = new BasicDBObject();
            doc3.put("first", "Larry");
            doc3.put("last", "Wall");
            doc3.put("email", "larryw@perl.org");
            doc3.put("mobile", "987 654 3210");
            contacts.update(criteria, doc3);
            
            // Query and display the document for first = "Larry" from the collection contacts
            System.out.printf("Document for Larry [after update fix]:\n");
            criteria = new BasicDBObject();
            criteria.put("first", "Larry");
            obj = contacts.findOne(criteria);
            if (obj != null) {
                System.out.println(obj);
            }
            
            // Delete the document for first = "James" from the collection contacts
            criteria = new BasicDBObject();
            criteria.put("first", "James");
            contacts.remove(criteria);
            
            // Query and display all the documents in the collection contacts
            System.out.printf("Documents in contacts [after removing James]:\n");
            cursor = contacts.find();
            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }
            
            // Delete all the remaining documents for the collection contacts
            contacts.remove(all);
            
            // Display the number of documents in the collection contacts
            System.out.printf("Number of documents in contacts [after remove all]: %d\n", contacts.count());
            
            // Drop the collection contacts
            contacts.drop();
            
            // Display all the collections in the database mydb
            System.out.printf("List of collections: %s\n", db.getCollectionNames());
        }
        catch (Exception ex) {
            ex.printStackTrace(System.err);
        }
        finally {
            // Close the database connection
            if (client != null) {
                client.close();
            }
        }
        
        System.out.printf("Done !!!\n");
    }
}

Let us try to understand the source code from Mongo_1.java above:

Executing Mongo_1.java will generate the following output:

Output.2

Connected to MongoDB @ localhost:27017
List of collections: [system.indexes]
List of collections: [contacts, system.indexes]
Number of documents in contacts: 1
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaa9e"} , "first" : "Bill" , "last" : "Gates" , "email" : "bill.gates@microsoft.com" , "mobile" : "123 456 7890"}
Documents in contacts:
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaa9e"} , "first" : "Bill" , "last" : "Gates" , "email" : "bill.gates@microsoft.com" , "mobile" : "123 456 7890"}
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaa9f"} , "first" : "James" , "last" : "Gosling" , "email" : "jgosling@oracle.com" , "mobile" : "234 567 8901"}
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa0"} , "first" : "Larry" , "last" : "Wall" , "email" : "larryw@perl.org"}
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa1"} , "first" : "Guido" , "middle" : "van" , "last" : "Rossum" , "email" : "gvr@python.org" , "mobile" : "345 678 9012"}
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa2"} , "first" : "Anders" , "last" : "Hejlsberg" , "email" : "anders@microsoft.com" , "mobile" : "456 789 0123"}
Document for Larry:
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa0"} , "first" : "Larry" , "last" : "Wall" , "email" : "larryw@perl.org"}
Document for Bill Gates:
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaa9e"} , "first" : "Bill" , "last" : "Gates" , "email" : "bill.gates@microsoft.com" , "mobile" : "123 456 7890"}
First and Last name(s) in contacts:
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaa9e"} , "first" : "Bill" , "last" : "Gates"}
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaa9f"} , "first" : "James" , "last" : "Gosling"}
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa0"} , "first" : "Larry" , "last" : "Wall"}
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa1"} , "first" : "Guido" , "last" : "Rossum"}
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa2"} , "first" : "Anders" , "last" : "Hejlsberg"}
First and Last name(s) [without _id] in contacts:
{ "first" : "Bill" , "last" : "Gates"}
{ "first" : "James" , "last" : "Gosling"}
{ "first" : "Larry" , "last" : "Wall"}
{ "first" : "Guido" , "last" : "Rossum"}
{ "first" : "Anders" , "last" : "Hejlsberg"}
first = Larry, last = Wall
First and Last name(s) [without _id with limit 3] in contacts:
{ "first" : "Bill" , "last" : "Gates"}
{ "first" : "James" , "last" : "Gosling"}
{ "first" : "Larry" , "last" : "Wall"}
Document for Larry [after update]:
Document for Larry [after update using mobile]:
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa0"} , "mobile" : "987 654 3210"}
Document for Larry [after update fix]:
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa0"} , "first" : "Larry" , "last" : "Wall" , "email" : "larryw@perl.org" , "mobile" : "987 654 3210"}
Documents in contacts [after removing James]:
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaa9e"} , "first" : "Bill" , "last" : "Gates" , "email" : "bill.gates@microsoft.com" , "mobile" : "123 456 7890"}
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa1"} , "first" : "Guido" , "middle" : "van" , "last" : "Rossum" , "email" : "gvr@python.org" , "mobile" : "345 678 9012"}
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa2"} , "first" : "Anders" , "last" : "Hejlsberg" , "email" : "anders@microsoft.com" , "mobile" : "456 789 0123"}
{ "_id" : { "$oid" : "53251446e4b0c2d52bfaaaa0"} , "first" : "Larry" , "last" : "Wall" , "email" : "larryw@perl.org" , "mobile" : "987 654 3210"}
Number of documents in contacts [after remove all]: 0
List of collections: [system.indexes]
Done !!!

References

Hands-on MongoDB :: Part-1