Mongo Db Tutorial

Name of Innovation

Mongo Db Tutorial

February 3, 2017 NoSQL Tutorial 0

Start MongoDB

  • Enter following commands

1.) cd 
2.) /home/hduser/start_mongodb.sh
Wait for approx 30 seconds
3). type mongo
you should see mongodb prompt as below
> db

 

In case if you have difficulty in connecting – try setting following –

 

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
Check the DBs already existing in your setup:

> show dbs
local  0.078GB
woir   0.078GB

Delete all the DBs existing to start your tutorial from scratch. To delete / drop a database, make sure you have selected the database and then do this:

> use woir
> db.dropDatabase()
{"dropped" : "scores", "ok" : 1 }

To select a database:

> use sports
switched to db sports

To find out the currently selected database:

> db.getName()
sports

To delete / drop a database, make sure you have selected the database and then do this:

> use sports
> db.dropDatabase()
{"dropped" : "scores", "ok" : 1 }

Create and select DB again

> use sports
switched to db sports

To see the collections in a databases:

> show collections

or

> db.getCollectionNames()

Let’s create a new database named “sports” – it is lazy creation:

> use sports
switched to db sports
> db.information.insert({name:"Andre Adams",year:1975} )

That above commands resulted in the creation of the new database named “sports”. In the process a new collection called “information” was also created in the database.

Create / add data in MongoDB

To create documents in a collection:

> db.information.insert({name:"Brendon McCullum",year:1981})
> db.information.insert({name:"Carl Cachopa",year:1986})

The two commands above added two more documents to the collection named “information” in the “sports” database.

You could have done the same thing using the save command instead of the insert command.

> db.information.save({name:"Chris Cairns",year:1970}) 
> db.information.save({name:"Chris Harris",year:1969})

The difference between insert and save is this:

insert will always add a new document.
save does an insert if there is no _id key in the object it receives, else it does an update.

To read data from a collection

> db.information.find()
> db.information.find()
{ "_id" : ObjectId("5894174f3b9f8fd81c8b9768"), "name" : "Andre Adams", "year" : 1975 }
{ "_id" : ObjectId("589417583b9f8fd81c8b9769"), "name" : "Brendon McCullum", "year" : 1981 }
{ "_id" : ObjectId("5894175e3b9f8fd81c8b976a"), "name" : "Carl Cachopa", "year" : 1986 }
{ "_id" : ObjectId("5894176c3b9f8fd81c8b976b"), "name" : "Chris Cairns", "year" : 1970 }
{ "_id" : ObjectId("589417723b9f8fd81c8b976c"), "name" : "Chris Harris", "year" : 1969 }

To limit it to just two:

> db.information.find().limit(2)
{ "_id" : ObjectId("5894174f3b9f8fd81c8b9768"), "name" : "Andre Adams", "year" : 1975 }
{ "_id" : ObjectId("589417583b9f8fd81c8b9769"), "name" : "Brendon McCullum", "year" : 1981 }

Similar to using find().limit(1),  equivalent –

>db.information.findOne()
{
"_id" : ObjectId("5894174f3b9f8fd81c8b9768"),
"name" : "Andre Adams",
"year" : 1975
}

What if you want to conditionally find documents?

> db.information.find({year:{$lt:1981}})
{ "_id" : ObjectId("5894174f3b9f8fd81c8b9768"), "name" : "Andre Adams", "year" : 1975 }
{ "_id" : ObjectId("5894176c3b9f8fd81c8b976b"), "name" : "Chris Cairns", "year" : 1970 }
{ "_id" : ObjectId("589417723b9f8fd81c8b976c"), "name" : "Chris Harris", "year" : 1969 }

$lt is one of the many conditional operators in MongoDB. Here are the rest.

$lt - ' $lte - ' $gte - '>='
$ne - '!='
$in - 'is in array'
$nin - '! in array'

And how do we do an ‘equal to’ (==) query? Just match the value for the queried key:

> db.information.find({year:1992})
{ "_id" : ObjectId("5894174f3b9f8fd81c8b9768"), "name" : "Andre Adams", "year" : 1975 }

We can even use regular expressions in our queries!

> db.information.find({name:{$regex: /Chri|dre/i}})
{ "_id" : ObjectId("5894174f3b9f8fd81c8b9768"), "name" : "Andre Adams", "year" : 1975 }
{ "_id" : ObjectId("5894176c3b9f8fd81c8b976b"), "name" : "Chris Cairns", "year" : 1970 }
{ "_id" : ObjectId("589417723b9f8fd81c8b976c"), "name" : "Chris Harris", "year" : 1969 }

Now let’s try a more complicated use of regex in a query.

> var names = ['Andre', 'Chri']
> names = names.join('|');
> var re = new RegExp(names, 'i')
> db.information.find({name:{$regex: re}})
{ "_id" : ObjectId("5894174f3b9f8fd81c8b9768"), "name" : "Andre Adams", "year" : 1975 }
{ "_id" : ObjectId("5894176c3b9f8fd81c8b976b"), "name" : "Chris Cairns", "year" : 1970 }
{ "_id" : ObjectId("589417723b9f8fd81c8b976c"), "name" : "Chris Harris", "year" : 1969 }

What if you want to get only some fields in the result?

> db.information.find({year:{'$lt':1994}}, {name:true})
{"_id" : ObjectId("5894174f3b9f8fd81c8b9768"), "name" : "Andre Adams" }
{ "_id" : ObjectId("589417583b9f8fd81c8b9769"), "name" : "Brendon McCullum" }
{ "_id" : ObjectId("5894175e3b9f8fd81c8b976a"), "name" : "Carl Cachopa" }
{ "_id" : ObjectId("5894176c3b9f8fd81c8b976b"), "name" : "Chris Cairns" }
{ "_id" : ObjectId("589417723b9f8fd81c8b976c"), "name" : "Chris Harris" }
To get more than one exclusive fields 
 db.information.find({year:{'$lt':1994}}, {name:true, father'sname:true}). 

The _id field is always returned by default.

To hide it use following –

> db.information.find({year:{'$lt':1994}}, {_id:false})

Try to hide name from the o/p

> db.information.find({year:{'$lt':1994}}, {name:false})
{ "_id" : ObjectId("5894174f3b9f8fd81c8b9768"), "year" : 1975 }
{ "_id" : ObjectId("589417583b9f8fd81c8b9769"), "year" : 1981 }
{ "_id" : ObjectId("5894175e3b9f8fd81c8b976a"), "year" : 1986 }
{ "_id" : ObjectId("5894176c3b9f8fd81c8b976b"), "year" : 1970 }
{ "_id" : ObjectId("589417723b9f8fd81c8b976c"), "year" : 1969 }

BTW field inclusion and exclusion cannot be used together.

Dot Notation -: so let’s create some documents in a collection named ‘articles’:

> db.articles.insert({title:'The Amazingness of MongoDB', meta:{author:'Mike Vallely', date:1321958582668, likes:23, tags:['mongo', 'amazing', 'mongodb']}, comments:[{by:'Steve', text:'Amazing article'}, {by:'Dave', text:'Thanks a ton!'}]})

> db.articles.insert({title:'Mongo Business', meta:{author:'Chad Muska', date:1321958576231, likes:10, tags:['mongodb', 'business', 'mongo']}, comments:[{by:'Taylor', text:'First!'}, {by:'Rob', text:'I like it'}]})

> db.articles.insert({title:'MongoDB in Mongolia', meta:{author:'Ghenghiz Khan', date:1321958598538, likes:75, tags:['mongo', 'mongolia', 'ghenghiz']}, comments:[{by:'Alex', text:'Dude, it rocks'}, {by:'Steve', text:'The best article ever!'}]})

Note the dot notation

> db.articles.find({'meta.author':'Chad Muska'})
> db.articles.find({'meta.likes':{$gt:10}})

Searching array:

> db.articles.find({'meta.tags':'mongolia'})

When the key is an array, the database looks for the object right in the array.

> db.articles.find({'comments.by':'Steve'})

Refer to array indexes:

> db.articles.find({'comments.0.by':'Steve'})

Always remember that a quoted number is a string, and is not the same as the actual number. For example:

> db.employee.find({salary:100})

is totally different from

> db.employee.find({salary:'100'})

Try following two –

> db.information.find('this.year > 1971 && this.name != "Andre Adams"')

 

> db.information.find({year:{$gt:1971}, name:{$ne:'Andre Adams'}})

Both above are same.

MongoDB has another operator called $where using which you can perform SQL’s WHERE-like operations.

> db.information.find({$where: 'this.year > 1971'})
{ "_id" : ObjectId("5894174f3b9f8fd81c8b9768"), "name" : "Andre Adams", "year" : 1975 }
{ "_id" : ObjectId("589417583b9f8fd81c8b9769"), "name" : "Brendon McCullum", "year" : 1981 }
{ "_id" : ObjectId("5894175e3b9f8fd81c8b976a"), "name" : "Carl Cachopa", "year" : 1986 }

and

> db.information.find({name:'Andre Adams', $where: 'this.year > 1970'})
{ "_id" : ObjectId("5894174f3b9f8fd81c8b9768"), "name" : "Andre Adams", "year" : 1975 }

 

Update data in MongoDB

Document replacement-

> db.information.update({name:"Andre Adams"}, {father:'Stephen Adams'})

 

Appending –

 

> db.information.update({name:"Andre Adams"}, {'$set':{father:'Stephen Adams', players:['Crickets', 'Hockey']}})

Update an array

> db.information.update({name:"Andre Adams"}, {'$push':{players:'Kabbadi'}})
> db.information.update({name:"Andre Adams"}, {'$push':{players:'Tennis'}})

Eh, we need to remove something from the cast array. We do it this way:

db.information.update({name:"Andre Adams"}, {'$pull':{players:'Kabbadi'}})

Delete data in MongoDB

 

> db.information.update({name:'Andre Adams'}, {$unset:{players:1}})

Delete a field from all the document of a collection:

> db.information.update({$unset:{players:1}}, false, true)

The false parameter if for upsert option, true is for multiple option. We set multiple option to true because we want to delete them all from the collection.

Delete all documents from a collection with name Andre Adams

> db.information.remove({name:'Andre Adams'})

Drop all the documents

> db.information.remove()

The above command truncates the collection.

Delete / drop a collection-

> db.information.drop()

To delete a database select the database and call the db.dropDatabase() on it:

> use information
> db.dropDatabase()
{"dropped" : "information", "ok" : 1 }

Get the count of Documents / Records

 

> db.information.count({})

This will return the total number of documents in the collection named information with the value of year more than 1970:

> db.information.count({year:{$gt:1990})

 

 

Screen Shot 2017-02-03 at 11.32.13 AM