Skip to content

DB Mongodb Cheat sheet

gpawade edited this page Feb 11, 2018 · 1 revision

Mongo Database

  • is cross platform, document oriented database
  • high performance, high availability and easy scalability
  • work on concept of collection & document
  • is written in c++

Basic Concept

Database

  • physical container for collection
  • each database gets its own set of file on the file system.

Collection

  • is group of mongodb document
  • is the equivalent of RDBMS table
  • do not enforce a schema

Document

  • is set of key values
  • have dynamic schema
  • is equivalant of RDBMS table row

why mongodb

  • Document oriented db
  • index on any attribute
  • replication and high availability
  • auto-sharding
  • rich queries

Running Mongod

Through Shell

# start mongodb server
$ mongod --dbpath=data/	

Through service in ubuntu

$ sudo service mongod start

Note - default port : 27017

Connecting to Mongo Db

#connect to remote server
$ mongo "mongodb://mongoserver.net:27017?replicaSet=Cluster0-shard-0" --authenticationDatabase admin --ssl --username user --password pwd

# connect to default local server
$mongo 	

Run mongo db shell

# connect to default local server
$mongo 				- run mongo db shell

> use <db name>		- swith database or create database if not exist already
> db 				- to check currently selected database
> show dbs 			- check database list
> show collections	- show list of collection in current db
> db.dropDatabase()	- drop the database

db statistics

> db.stats()

db Help

> db.help()

Create Collection

> db.creatCollection(name,option)

Get Collection Help

> db.<collection_name>.help()

Supported DataType

  • String
  • Integer
  • Boolean
  • Double
  • Min/Max Keys
  • Arrays
  • Timestamp
  • Date - Unix time format
  • Object
  • Object Id
  • Null
  • Code - datatype use to store the java script code
  • Regular Express - use to store the regular exp.

INSERT document

> db.mycollection.insert({name:'movie name', releasedate:'date'});
Note

_id is 12 byte hexadecimal number unique for every document. 12 bytes are devided as follows:

  • 4 bytes timestamp
  • 3 bytes machine id
  • 2 bytes proccess id
  • 3 bytes incrementers

filter sample

#equality
{ "name"  : "search value" }

#less than  
{ "price" : {$lt : 50} }
# less than equal
{ "price" : {$lte : 50}}

# greater than
{ "price" : {$gt : 50} }
# greater than equal
{ "price" : {$gte : 50}}

# not equal
{ "price" : {$ne : 50} }

# And statement
{ 
	key1:value1, 
	key2:value2 
}

# OR statement
{
  $or: [
     {key1: value1}, {key2:value2}
  ]
}


# Array Exact Match
{ "amenities" : ["pool", "parking","wifi"]}

# Array with single element match
{ "amenities" : "wifi" }

# Array with position element
{ "amenities.0" : "pool"}

Note -

use .pretty() to display result in formatted

UPDATE Document

> db.myCollection.update(SELECTIOIN_CRITERIA, UPDATED_DATA)

e.g.
	> db.mycol.update({'title':'MongoDB Overview'}, {$set:{'title':'New MongoDB Tutorial'}})

Save

- replace existing document with new one

> db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})

REMOVE Document

> db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)

> db.COLLECTION_NAME.remove(DELETION_CRITERIA, 1)    - remove only one  

> db.COLLECTION_NAME.remove()		- remove all document

e.g.
	> db.Users.remove( { status : "D" } )

Projection

- select only necessary data rather than selecting whole of the data of document

> db.COLLECTION_NAME.find({},{ _id: 0, name :1})
				this will return only name parameter and hide the _id param

Limit

- limit the record to return 

> db.COLLECTION_NAME.find().limit(NUMBER)

Skip

- skip the record to return 

> db.COLLECTION_NAME.find().skip(NUMBER)

Sort Document

> db.COLLECTION_NAME.find().sort({KEY:1})

	  - 1 for ascending , -1 for descending

Index

- Indexes support the efficient resolution of queries

> db.COLLECTION_NAME.ensureIndex({KEY:1})
		1 for create index in ascending order
		-1 for decending order
	* Optional option
		background Boolean
		unique		Boolean
		name 		name of index
		...

Aggreagate

	Syntax
		db.<collection>.aggregate(aggregate_operation)
	e.g.
		db.myCol.aggregate([ { 
			$group : { _id : "$column1",  num : { $sum : 1}   }
		} ])

		simillar with
		select column1, count(*)
		from mycol
		group by column1

	@ Expression
		$sum
		$avg
		$min
		$max

Backup

> mongodump

-- Restore 
> mongorestore

Replication

  • is the process of synchronization data across multiple server
  • replication protect database from the loses of single server
  • with addition copy of data, you can dedicate one to disaster recovery, reporting, or backup

Sharding

  • Sharding is the process of storing data records across multiple machine.
  • sharding solve the problem of horizontal scaling
  • with sharding, you add more machine to support data growth and demands of read & write operations.

Tool

MongoDB Compass

As the GUI for MongoDB, MongoDB Compass allows you to make smarter decisions about indexing, document validation, and more.

  • Visually explore the structure of data in your database
  • Run ad hoc queries in seconds
  • View and optimize your query performance
  • Interact with your data with full CRUD functionality
  • Create and modify rules that validate your data