MongoDB is an open source, document oriented database created in 2009 and classified as NoSQL database. Although MongoDB is written in C++, drivers and client libraries are typically written in their respective languages.
In MongoDB, a record is a document, and documents are stored in a JSON like format. Precisely, in MongoDB documents are stored in BSON format which is a binary representation of JSON documents.
Every MongoDB document has an unique identifier, similar to a primary key a relational DBMS. This unique identifier is called ObjectID and its value consists of 12-bytes where the first 4-bytes are the timestamp of the document creation, followed by 3-bytes machine id, 2-byte process id and 3-byte counter.
Key features of MongoDB
- in MongoDB, you can set an index to any attribute, even on embedded attribute. These are called embedded indexes.
- supports map/reduce framework for batch processing of data and aggregation operation.
- supports various programming languages, such as C, C#, Java, Perl, Ruby, Scala, PHP, Python, others too. For a complete list of supported languages see this page.
Advantages of using document oriented databases
- reduce, or eliminate the needs for expenses joins
- allows for a dynamic schema that can be change on the fly. In other words, you can change the structure of documents simply by adding new fields or delete existing ones
Disadvantages
- mongoDB doesn’t supports joins
- mongoDB doesn’t supports transactions. Instead it provides atomic operations on a single document
- has no configurable cache
MongoDB installation on MAC OS:
1 2 |
brew install mongodb ==> Downloading https://homebrew.bintray.com/bottles/mongodb-4.0.3_1.mojave.bottle.tar.gz==> Downloading from https://akamai.bintray.com/ab/ab08fc6748bc37d0e2ec209126db3236bd80a2ae4edee2f6fc34d96481fe34c7?__gda__=exp=1554889733~hmac=3fd614cd689fa2aeea764d369f######################################################################## 100.0%==> Pouring mongodb-4.0.3_1.mojave.bottle.tar.gz==> CaveatsTo have launchd start mongodb now and restart at login: brew services start mongodbOr, if you don't want/need a background service you can just run: mongod --config /usr/local/etc/mongod.conf==> Summary /usr/local/Cellar/mongodb/4.0.3_1: 18 files, 258.1MB |
After installation run the following command to start MongoDB:
1 |
mongo start |
Mongo DB shell commands:
- mongo – get a new mongoDB shell
- use DATABASE-NAME – work with the specified database
- show collections – list all collection in a database
- cls – clear the screen
The mongo shell supports up and down arrow key to navigate through commands history. The tab key can be used to autocomplete or to list the available possibilities.
Mongo DB databases
MongoDB supports creation of databases on the fly. This means you are not require to create a database before start working with it.
Mongo DB commands:
- show dbs – show a list of all the databases;
- use admin – switch to the admin database; If the database doesn’t exist it will be created
- db – used to check the current database
- db.createUser({user: ‘demo’, pwd: ‘demo’, roles:[‘readWrite’, ‘dbAdmin’]})
- show users
- db.stats() – to get stats about MongoDB server. This will show the database name, number of collection and documents in the database.
- db.help() – to get a list of commands. This will give you a list of commands as shown in the following screenshot.
- db.dropDatabase() – used to drop a existing database. If you have not selected any database, then it will delete default ‘test’ database.
- show collections – used to check the available collections
Query MongoDB commands:
- db.COLLECTION-NAME.getIndexes() – get the indexes in the specified collection. This command will not include the automatic index which is produced on the ID field.
- db.COLLECTION-NAME.save({_id:1, firstName: John, lastName: Doe}) – save a document in the collection
- db.COLLECTION-NAME.find() – query data within mongo db collection. There is also findOne() method that return only one document. Additionally you can use pretty() to format the result.
- db.COLLECTION-NAME.find({key:value}) – filter the collection to the match value
- db.COLLECTION-NAME.find({age:{$lt:23}}) – filter the collection where age is less than 23
- db.COLLECTION-NAME.find({age:{$lte:23}}) – filter the collection where age is equal or less than 23
- db.COLLECTION-NAME.find({age:{$gt:23}}) – filter the collection where age is greater than 23
- db.COLLECTION-NAME.find({age:{$gte:23}}) – filter the collection where age is equal with, or greater than 23
- db.COLLECTION-NAME.find({age:{$gt:18, $lt:23}}) filter the collection where age is between 18 and 23
- db.COLLECTION-NAME.find({age:{$in:[18, 21]}}) – filter the collection and return the documents where age is 18 or 21
- db.COLLECTION-NAME.find().limit(NUMBER) – limit the mongoDB results to the specified NUMBER
- db.COLLECTION-NAME.find().limit(NUMBER).skip(NUMBER)
- db.COLLECTION-NAME.find().sort({key:sortOrder}) – sort results according to the given sort order
- db.COLLECTION-NAME.find().explain()
- mongotop, mongostat
Update MongoDB commands:
- db.COLLECTION-NAME.update({_id:1}, {firstName: Joe, lastName: Doe})
- db.COLLECTION-NAME.update({_id:1}, {$set:{age: 36}}) -> this command will add a new field to the JSON document
- db.COLLECTION-NAME.update({_id:1}, {$unset:{age: ‘any_value’}}) -> this command will remove a field from the JSON document
- db.COLLECTION-NAME.update({_id:1}, {$rename:{‘name’: ‘firstName’}}) -> this command will rename the field name into firstName
- db.COLLECTION-NAME.update({userType:1}, {$set:{age: 21}}, {multi: true}) -> this command will update multiple records (the ones with userType = 1)
In MongoDB, the update command is atomic at the document level, meaning that Mongo locks the document and apply the updates without wondering that some other process may update the document until we finish our changes.
Delete documents in MongoDB:
- db.COLLECTION-NAME.remove() – delete whole documents from the collection
- db.COLLECTION-NAME.remove({_id:1}) – delete the document with the given _id
- db.COLLECTION-NAME.drop() -> removes the entire collection
Adding an index to MongoDB collection
- todo – simple index. for one field
- create embedded indexes
MongoDB aggregation framework
MongoDB aggregation framework is a tool for data analysis which is used to summarize data in order to create new value from the data we have in our database.
Temporarily access a different database
In MongoDB you can access another database without change the current database. This task can be achieved by using the getSiblingDB() command. In the following example, we are in demo database, and accessing test database:
1 2 |
use demo; db.getSiblingDB('test').getCollectionNames(); |
MongoDB Web Interface
MongoDB web interface can be accessed at the port number +1000 than the port on which mongo server is running. For example, the default port for mongo server is 27017 which implies you can access mongoDB web interface at the port 28017.
Further Learnings:
Introduction to MongoDB – w3resource.com
MongoDB Tutorial – tutorialspoint.com
http://mongodb-tools.com/tool/mongohub/