MongoDB - Document Database

MongoDB is an open source, cross-platform document database, classified as a NoSQL database. MongoDB moves away from the traditional relational database structure, using JSON-like dynamic documents, which makes integrating data faster and simpler. [1]

Key Features

  • Document-oriented

Unlike storing title and author across two relational structures, in MongoDB you can store the title, author, and other title-related information together in a single document called Book.

  • Ad hoc queries

MongoDB supports queries by field, range, and regular expression. Queries can return specific fields of the matched documents, and can also include user-defined JavaScript functions.

  • Indexing

Any field in a MongoDB document can be indexed

  • Replication

MongoDB provides high-availability replication; a replica set contains two or more copies of the data. Each copy can become the primary or a secondary at any time. The primary handles reads and writes, while secondaries keep replicating data from the primary. When the primary goes offline, a secondary automatically becomes the new primary.

  • Load balancing

MongoDB can run across multiple servers, load-balancing and replicating data, ensuring the system starts up and keeps running in the event of a hardware failure.

  • File storage

MongoDB can be used as a file system, which is helpful for load balancing and data replication. This feature, called GridFS, is included in the MongoDB drivers.

Installation

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
echo "deb http://repo.mongodb.org/apt/debian wheezy/mongodb-org/3.0 main" >> /etc/apt/sources.list.d/mongodb-org-3.0.list
apt-get update
apt-get install mongodb-org

Configuration

  • /etc/mongod.conf mongoDB’s configuration file

  • /var/lib/mongodb data files

  • /var/log/mongodb log files

Getting Started

  • Document

A document is the basic unit of data in MongoDB, very similar to a row in a relational database. A document is an ordered set of key-value pairs, where keys are strings and values can be many different data types. Every document must have an _id key. The value of that key defaults to the ObjectId type

  • Collection

A collection is a group of documents, equivalent to a table. Within a collection, each document’s _id is unique.

  • Database

Multiple collections make up a database

CRUD Operations

  • Insert

db.test.insert({“”:}) inserted data must be smaller than 16M

  • Delete

db.test.remove({“”:}) the remove function accepts key-value parameters as the deletion condition

  • Update

    • $set

      $set is used to update a key’s value; if the key doesn’t exist, it’s created. db.blog.update({“_id”:ObjectId(“5603697db13466f29ba8e673”)},{“$set”:{“fa”:”War and peace”,”wow”:”lol”}})

    • $unset

      $unset is used to clear a key’s value db.blog.update({“_id”:ObjectId(“5603697db13466f29ba8e673”)},{“$unset”:{“fa”:1}})

    • $inc

      $inc is used to increase a key’s value; if the key doesn’t exist, it’s created. db.blog.update({“_id”:ObjectId(“5603697db13466f29ba8e673”)},{“$inc”:{“fa”:55}})

    • upsert

      Setting update’s third parameter to true enables upsert, which can avoid race conditions db.blog.update({“_id”:ObjectId(“5603697db13466f29ba8e673”)},{“$inc”:{“fa”:55}}, true)

    • Updating multiple documents

      By default, update only updates the first document matching the condition. To update multiple documents, set update’s fourth parameter to true db.blog.update({“title” : “second blog post”},{“$set”:{“123”:456}},true,true)

  • Query

mongoDB uses find to query documents within a collection.

db.blog.find()

Returns all documents in the blog collection in bulk

db.blog.find({“age”:27})

Returns documents whose key-values include {“age”:27}

db.blog.find({“title”:”second”, “age”:27})

Returns documents whose key-values include {“title”:”second”} AND {“age”:27}

find’s second parameter is used to restrict which keys of the matched documents are returned.

db.blog.find({“title” : “second blog post”}, {“conntent”:1})

The return value only includes the _id and conntent keys

db.blog.find({“title” : “second blog post”}, {“conntent”:0, “title”:0})

The return value excludes the conntent and title keys

$lt $lte $gt $gte $ne correspond to < <= > >= ≠

db.blog.find({“age”:{“$gte”:18,”$lt”:30}})

Returns documents where age is greater than 18 and less than 30

File Storage Operations

File storage is based on the binary data type; below, python is used to perform file storage operations

from pymongo import MongoClient
client = MongoClient()
db = client.test
from bson import binary
file = open('test.txt', 'rb')
bin = binary.Binary(file.read())
db.test.insert({"file":bin})
file.close()

Verify

cursor = db.test.find()
for document in cursor:
print (document)

Write

cursor = db.test.find_one()
file = open("buff.txt","wb")
file.write(cursor['file'])
file.close()

GridFS

GridFS is used to support files larger than 16MB; files under 16M can simply be stored as documents. GridFS’s approach is: split a large file into multiple chunks, and store each chunk as an independent document.

mongofiles put index-bottom.png
mongofiles list
mongofiles gett index-bottom.png

References