MongoDB

  1. Overview
    1. MongoDB is a popular, free document-oriented database
    2. A record is a MongoDB document, a data structure composed of field/value pairs, similar to JSON objects
      {
      	name: "Sue",
      	gpa: 3.1,
      	interests: ["biking", "reading"]
      }
      
    3. MongoDB documents are BSON documents (BSON is a binary representation of JSON with additional type information)
    4. Documents are stored in collections, groups of related documents that have a set of shared common indexes (like a table)
    5. Helpful SQL to MongoDB Mapping Chart
  2. Install
    1. Download the Windows 64-bit zip file
    2. Unzip the file
    3. Copy the extracted directory to your desktop
    4. Open a command window, cd the MongoDB bin directory and run the daemon
      C:\path_to_mongodb\bin>mongod
      
    5. Leave running as long as you want to use MongoDB
    6. Press Ctrl-C or close the window to kill the daemon
  3. Start mongo shell
    1. Open a command window and run mongo
      C:\path_to_mongodb\bin>mongo
      MongoDB shell version: 2.6.6
      connecting to: test
      
    2. Looks for a database server listening on port 27017 on the localhost interface
    3. Helpful commands:
      1. help
      2. quit()
  4. Database operations (CRUD)
    1. Selecting a database
      1. Default database is test
      2. db command shows current database
        > db
        test
        
      3. Use a different database
        use mydb
        
    2. Insert a document with db.collection.insert()
      1. Add a stu to the students collection
        stu = {
        	name: "sue",
        	gpa: 3.1,
        	interests: ["biking", "reading"]
        }
        
        db.students.insert(stu);
        
        Returns a WriteResult object with the status of the operation:
        WriteResult({ "nInserted" : 1 })
        
      2. See the document inserted
        db.students.find()
        
        Returns the following:
        "_id" : ObjectId("54b44f77aed6aaa16e32ab0e"), "name" : "sue", "gpa" : 3.1, "interests" : [ "biking", "reading" ] }
        
      3. Inserted documents are assigned a unique _id field
      4. Documents can also be inserted in bulk
        students = 
        	[
        		{
        			name: "Sue",
        			gpa: 3.1,
        			interests: ["biking", "reading"]
        		},
        		{
        			name: "Bob",
        			gpa: 3.8,
        			interests: ["hiking"]
        		},
        		{
        			name: "Larry",
        			gpa: 2.5,
        			interests: ["volleyball", "gaming", "fantasy football"]
        		}
        	];
        
        db.students.insert(students);
        
        Returns BulkWriteResult object with the status of the operation:
        BulkWriteResult({
                "writeErrors" : [ ],
                "writeConcernErrors" : [ ],
                "nInserted" : 3,
                "nUpserted" : 0,
                "nMatched" : 0,
                "nModified" : 0,
                "nRemoved" : 0,
                "upserted" : [ ]
        })
        
    3. Query for documents
      1. Use db.collection.find() to get a cursor to the retrieved docs
        db.students.find( {} )   // Returns all documents
        db.students.find()       // Same thing
        
      2. Specify equality condition
        // Returns only Sue
        db.students.find( { name: 'Sue' })
        
        // To search by ID
        db.students.find( { "_id" : ObjectId("54ed06e82c917228271b581a") })
        
      3. Use query selectors
        // Returns Larry whose GPA is <= 3.0
        db.students.find( { gpa: { $lte: 3.0 } } );
        
        // Returns Sue whose gpa is > 3.0 and name is one of these three
        db.students.find( { gpa: { $gt: 3.0 }, 
        	name: { $in: ['Sue', 'Susan', 'Susie'] } } );
        
        // Returns Bob (gpa >= 3.5) and Larry (interest includes volleyball)
        db.students.find( 
        	{ 
        		$or: [ { gpa: { $gte: 3.5 } }, 
        		       { interests: { $in: [ 'volleyball', 'running' ] } } ]
        	}
        );
        
      4. Use dot notation to match embedded documents
        stu = {
        	name: "Sue",
        	gpa: 3.1,
        	interests: ["biking", "reading"],
        	
        	// Embedded document
        	address: {
        		city: "Dallas",
        		state: "TX"
        	}
        }
        
        db.students.insert(stu);
        
        // Returns Sue
        db.students.find( { 'address.city': 'Dallas' } );
        
    4. Modify documents with db.collection.update()
      1. Three parameters to update()
        1. conditions document to find the documents to update
        2. operations document specifying the modification
        3. options document
      2. Example using $set operator
        // Find Sue and change her age and degree
        db.students.update(
        	{ name: "Sue" },  // or { "_id" : ObjectId("54ed06e82c917228271b581a") }
        	{
        		$set: {
        			gpa: 3.5,
        			address: { city: "Denver", state: "CO" }
        		}
        	}
        );
        
        Returns a WriteResult object with the status of the operation:
        WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
        
      3. Update multiple documents with multi option
        // Update degree's institution for all students gpa > 3.0
        db.students.update(
        	{ gpa: { $gt: 3.0 } },
        	{ $set: { "address.city": "Searcy" } },
        	{ multi: true }
        );
        
    5. Remove documents with db.collection.remove()
      1. Remove all documents
        // Remove all!
        db.students.remove( {} );
        
        // Remove collection and associated indexes
        db.students.drop();
        
      2. Remove all documents matching search document
        // Delete all students with gpa < 3.0
        db.students.remove( { gpa: { $lt: 3.0 } } );
        
      3. Remove only one matching document using justOne parameter
        // Delete first student with gpa > 3.0
        db.students.remove( { gpa: { $gt: 3.0 } }, true );