Sunteți pe pagina 1din 23

Categories Series

Code
DATABASES
Getting Started with MongoDB - Part 1
by Matthew Setter 23 Nov 2011 85 Comments
4 8
Ready to get in and start learning about MongoDB, one of the coolest technologies for web
developers?
In this new series, you'll go from beginner to pro and be able to use Mongo just as easily as
MySQL in your web apps. But first, let's look at the basics.
Why MongoDB?
What if you could store the programmatic models almost
exactly like you model them?
In object-oriented development, we're encouraged to approach code development through
logical models, so that we can more readily conceptualise it in our mind. When we do this,
we're better able discern the logical operations used to interact with it and information that it
would contain at different times.
What if you could store the programmatic models almost exactly like you model them? What if
you could store them as they are instead of in a series of rows in tables? By learning about
MongoDB, you're going to be able to do just that!
In this series, we'll be learning everything from the basics of MongoDb, such as creating,
updating and deleting databases and records, to being able to perform complex searches for
data and elementary data mining with MapReduce. So, without much ado let's get started!
Note: This tutorial is done from the perspective of NIX based system a la Mac OSX, Linux
BSD and so on. But you should be able to follow along if you're running Windows pretty well as

there are builds for most platforms.


Step 1 : Installing Mongo
Ok, so here's where the fun begins. We're going to get started by installing Mongo. Go to the
MongoDb website and click on the downloads link.
This will bring you to a page where you can grab a build for your platform and architecture.
This tutorial only covers stable releases, so please do not grab a nightly build. Once it's
downloaded, please install it as per the requirements of your platform.
If you're on a Nix machine, then please use its package manager to install the latest version for
your platform.
With that out of the way, fire up a terminal and type in mongo . That will open up the Mongo shell
and let us get under way. All being well, you'll see output similar to below:
If you see that, then you're ready to go.
Step 2 : Creating a Database/Inserting Records
Initially, no database is created. But don't worry, they'll instantly be created when we start
inserting our records, which we're going to do right now. Copy the content below and paste it in
your mongo shell
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
db.nettuts.insert({
first: 'matthew',
last: 'setter',
dob: '21/04/1978',
gender: 'm',
hair_colour: 'brown',
occupation: 'developer',
nationality: 'australian'
});
db.nettuts.insert({
first: 'james',
last: 'caan',
dob: '26/03/1940',
gender: 'm',
hair_colour: 'brown',
occupation: 'actor',
nationality: 'american'
});
db.nettuts.insert({
All good? Excellent! To confirm that the database and accompanying records have been
created, type in the following command:
If everything went to plan, then you will see the following output:
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
first: 'arnold',
last: 'schwarzenegger',
dob: '03/06/1925',
gender: 'm',
hair_colour: 'brown',
occupation: 'actor',
nationality: 'american'
});
db.nettuts.insert({
first: 'tony',
last: 'curtis',
dob: '21/04/1978',
gender: 'm',
hair_colour: 'brown',
occupation: 'developer',
nationality: 'american'
});
db.nettuts.insert({
first: 'jamie lee',
last: 'curtis',
dob: '22/11/1958',
gender: 'f',
hair_colour: 'brown',
occupation: 'actor',
nationality: 'american'
});
db.nettuts.insert({
first: 'michael',
last: 'caine',
dob: '14/03/1933',
gender: 'm',
hair_colour: 'brown',
occupation: 'actor',
nationality: 'english'
});
db.nettuts.insert({
first: 'judi',
last: 'dench',
dob: '09/12/1934',
gender: 'f',
hair_colour: 'white',
occupation: 'actress',
nationality: 'english'
});
1 db.nettuts.find()
This shows that all of the records were created in the database. One thing to note before we go
any further is the id field. This is auto generated by Mongo for you, if you don't specify an id.
The reason is that every record must have a unique id field.
You can see that we have one record for each of the ones that we insert now we're ready to
start querying them.
Step 3 : Searching For Records
You remember the previous command? It retrieved and displayed every record in the database.
Helpful, yes, but how do you be more specific? How do you find all female actors, filtering out
the males? That's a good question and the answer is selectors.
Selectors
Selectors are to Mongo what where clauses are to SQL. As with where clauses, Mongo
selectors allow us to do the following:
specify criteria that MUST match. i.e., an AND clause
specify criteria that CAN optionally match. i.e., an OR clause
specify criteria that MUST exist
and much more...
Records That MUST Match
Let's start with a basic selector. Say that we want to find all actors that are female
. To accomplish that, you'll need to run the following command:
Here we have specified that gender must be equal 'f'.
Running that command will return the following output:
What if we wanted to search for male actors? Run the following command:
We'll get the following results:
1 db.nettuts.find({gender: 'f'});
1 db.nettuts.find({gender: 'm'});
Searching with Multiple Criteria
Let's step it up a notch. We'll look for male actors that are English.
Running that will return the following results:
What about male actors who are English or American. Easy! Let's adjust our earlier command
to include the Americans:
1 db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}]});
For that query, we'll see the following results:
Step 4 : Sorting Records
What if we want to sort records, say by first name or nationality? Similar to SQL, Mongo
provides the sort command. The command, like the find command takes a list of options
to determine the sort order.
Unlike SQL, however we specify ascending and descending differently. We do that as follows:
Ascending: -1
Descending: 1
Let's have a look at an example:
This example retrieves all male, English or American, actors and sorts them in descending
order of nationality.
1 db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'
, $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1});
What about sorting by nationality in descending order and name in ascending order? No
problem at all! Take a look at the query below, which is a modified version of the last one we
ran.
This time we retrieve the following results et:
You can see that this time Arnold Schwarzenegger is placed before Tony Curtis.
1 db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'
Step 5 : Limiting Records
What if we had a pretty big data set (lucky us, we don't) and we wanted to limit the results to just
2? Mongo provides the limit command, similar to MySQL and allows us to do just that. Let's
update our previous query and return just 2 records. Have a look at the following command:
From that command, we'll get the following results:
If we wanted the third and fourth records, i.e., skip over the first two? Once again, Mongo has a
function for that. Have a look at the further customisation of the previous command:
Running that will return the following results:
1 db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'
1 db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'
You can see from the original result set that the first two were skipped.
Step 6 : Updating Records
As expected, Mongo provides an option to update records as well. As with the find method
and SQL queries, you need to specify the criteria for the record that you want to modify, then the
data in that record that's going to be modified.
Let's say that we need to update the record for James Caan specifying that his hair is grey, not
brown. Well for that we run the update function. Have a look at the example below:
Now when you run that, if all went well, there won't be anything to indicate whether it was a
success or failure. To find out if the record was update properly, we need to search for it. So
let's do that.
After this you will see the following result:
1 db.nettuts.update({first: 'james', last: 'caan'}, {$set: {hair_colour: 'brown'
1 db.nettuts.find({first: 'james', last: 'caan'});
This shows that the update worked. One word of caution though, if you don't pass in the $set
modifier, then you will replace the record, if it's available, instead of updating it. Be careful!
Microsoft SQL
Server
microsoft.com/sql-server
Transform Your Information
Platform with Microsoft SQL
Server. Try Now!
Adverti sement
Step 7 : Deleting Records
I think by this stage, you have really started to get the idea of working with Mongo. That's right, if
you want to delete a record, you have to pass in a set of selectors, as you also would with SQL,
to determine the set of records to delete. If you don't do this, you will delete all records and the
database.
So, let's say that we don't want James Caan in our list of actors. Let's remove him from the
database using the following command:
As with update, no visible output is provided to indicate whether we were successful or not so
let's do a search to double check.
After this, you should see no results returned. If that's what you've found, then we've successfully
deleted James Caan from our database. But what if we want to delete all the records from the
database?
Well, to do that, just remove the selectors from the previous call to remove, as below.
After running both commands above, we'll see no output, indicating that the database, with all
records have now been removed.
Conclusion
1 db.nettuts.remove({first: 'james', last: 'caan'});
1 db.nettuts.find({first: 'james', last: 'caan'});
1
2
db.nettuts.remove();
db.nettuts.find();
In this rapid introduction to using MongoDB we looked at:
What Mongo is
How to install it
How to create, find, update and delete records
With this knowledge, you can go, practice, and learn more about this wonderful technology. If
you want more information, feel free to check out the MongoDb website or follow @mongodb
on Twitter.
In the next tutorial, we're going to start to learn more about complex queries. So stay tuned and
thank you so much for reading.
Update: The second part of this series has been posted and can be found here.
Adverti sement
Difficulty:
Intermediate
Length:
Short
Tagged with:
Databases Web Development NoSQL MongoDB
About Matthew Setter
Matthew Setter is a passionate, PHP-oriented, software engineer and educator, originally from
Queensland, Australia. Now in London, he is working hard to help educate his fellow developers through
Malt Blue as well as writing for various online publications.
Adverti sement
Related Posts
Human Anatomy Fundamentals: Advanced Facial Features
9 May 2014 In this tutorial we'll go into more details about the face, with features individualized by
gende...
Creating an RSS Feed Reader With the MEAN Stack
4 Apr 2014 In the last tutorial we installed the MEAN stack. Now, let's do some actual coding and build
an R...
Preventing Code Injection
17 Feb 2014 Often, websites seem to exist primarily to put something into a database in order to pull it
out ...
Using WordPress for Web Application Development: WP_User_Query
12 Feb 2014 In this series, we've been taking a look at how WordPress can be used to development
web applicat...
Mapping Relational Databases and SQL to MongoDB
6 Feb 2014 NoSQL databases have emerged tremendously in the last few years owing to their less
constrained s...
85 Comments Nettuts+ Login
Sort by Best Share
Join the discussion
Reply
Amar 3 years ago
There is a mistake In Step 4 (Sorting Records)
Ascending should be : 1
Descending should be : -1
Please make it change..

17
Reply
daGrevis 3 years ago
Got it.
This may help you to understand too:
MongoDB:
`{gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}`
MySQL:
`WHERE gender="m" AND (nationality="english" OR nationality="american")`

4
Alex 3 years ago daGrevis
Yes i think the male and english example was a mistake, allthough it may very well
work like so;
`db.nettuts.find({gender: m, $or: [{nationality: 'english'}]});`
I think this is how it should be written;
Favorite
Share
Share
Getting Started with MongoDB - Part 2
10 Jan 2012 Ready to continue learning about MongoDB, one of the coolest technologies for web
developers? In ...
Reply
I think this is how it should be written;
`db.nettuts.find({gender: m, nationality: 'english'});`

3
Reply
Matthew Setter 3 years ago Alex
Alex & daGrevis,
thanks for picking me up on a not so clear example. Much appreciated.
Matt


Reply
Moby a year ago Matthew Setter
and yet 2 years later it still hasn't been fixed!

3
Reply
w p 7 months ago Matthew Setter
Matt,
Why haven't the errors in this tut been corrected? There are people
paying for access to this site, it's not like somebodies hobby blog...


Reply
tvance929 8 months ago
Unless I missed something, James Caan's hair was brown to begin with... ? I changed it to
red since he always seems to be angry.

1
Reply
Theo 10 months ago
"What if you could store them as they are instead of in a series of rows in tables" So they
are store in a series of Documents and Collections. Seriously, what is the big difference?

1
Reply
Tasneem Hyder a year ago
lots of mistake..please update the content.

1
Reply
phil a year ago
brilliant ... well done.. thanks, very clear to learn how to start

1
Reply
Robert J. Moore 2 years ago
This is awesome, thanks! In case someone finds it useful, I recently built this MySQL to
MongoDB query translator tool for figuring out how to express different kinds of SQL queries
in Mongo syntax: www.querymongo.com

1
Code 2 Learn 3 years ago
A very interesting post. I have just started using Momgo DB for my Project and i think it is
Share
Share
Share
Share
Share
Share
Share
Share
Share
Reply
A very interesting post. I have just started using Momgo DB for my Project and i think it is
great tutorial to for the amateurs to start with.. Code 2 Learn
If interested in link exchange then please email me

1
Reply
daGrevis 3 years ago
> Well look for male actors that are English.
`db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}]});`
I don't understand this from logical aspect. Why there's 'or'? In my opinion, there should be
'and' because we want to find all people that are male **and** are English too. Not people
who are male or English because it would return also females that are English, right?
Please explain this to me, guys. I'm new to MongoDB. One thing I'm sure - it's exciting. :)
P.S. Superb review. Can't wait for next part! :)

1
Reply
Nav 3 years ago
As this is a tutorial aimed at those just getting started with MongoDB (and potentionally the
JSON format) it maybe of some use in terms of readability to be aware that adding the
pretty() function at the end of your query will format the output in the shell might (esp with
large records) make it easier to understand.
eg:
db.nettuts.find().pretty()
Looking forward to the rest of the series!

1
Reply
nik 2 years ago
Why not making a tut of something usefull like hbase or oracle g11?


Reply
Randy Ackerman 2 months ago
The gender of Jamie Lee Curtis should be "?", just saying.


Reply
Vishal Sachdeva 4 months ago
Buggy tutorial, pre assume many things, the installation process is incomplete (most tricky
part). Need a rework overall.


[c0d3r28] 5 months ago
There are several errors here, not to mention the steps are not consecutive, you need to
explain them clearly, instead of saying "its ok they will be created when you start" this is not
conducive to a getting started tutorial.
Share
Share
Share
Share
Share
Share
Reply
conducive to a getting started tutorial.


Reply
Drag'n'Drop 10 months ago
Excellent article! Thank you so much!


Reply
Ajedi32 a year ago
You know, aside from the use of the `$` character in the `$or` and `$set` modifiers, all of
those queries are syntactically valid Ruby code. ;)


Reply
hikingmike a year ago
Interesting DB, thanks for the article. One question though - since you didn't have to create
or define the database table before inserting into it, I wonder what happens if you do an
insert to a table and include a column name that wasn't specified in the first insert. Does it
happily accept it and just add it onto that record? Does it add the column to all records with
nulls? Does it give an error since that column doesn't exist? Also then what do you get as
output if you select on that column name, especially since all the other records won't have
that data?
Thanks!


Reply
Melcu a year ago hikingmike
It only add a colum in that record.


Reply
hikingmike a year ago Melcu
Ok cool. Now what about my last question, selecting on it?


Reply
mbokil a year ago
Wild stuff. Loved your tutorial. I needed to learn Mongo DB fast and this gave me the basics.
It amazes me how JS has taken over another field and literally obsoleted SQL. I am a JS
hacker so this is very appealing to me. Is there nothing left that JS has not taken over now?
Amazing. Mongo is a natural fit for JS web programmers. So our MVC is knockout.js and db
is now JS syntax. Cool stuff.


Reply
harjot 2 years ago
hi
i need to open existing mongodb database files on my machine (in fedora17) which is
created on another machine
m not able to open that database


rock 2 years ago
Share
Share
Share
Share
Share
Share
Share
Share
Reply
rock 2 years ago
it is very good and it is very useful


Reply
RNA 2 years ago
Hi,
I want to install mongoDB into my application specific unix environment. Can anyone help
me how to do that.


Reply
Karma Dice 2 years ago
You sir! Rock! Beautiful explanation. Thank you.


Reply
sundaram 2 years ago
The tutorial is simple, with examples and self explanatory containing screen dumps.
thanks


Reply
Fernando Lozano 2 years ago
Hi, Matthew!
Thanks for writing this tutorial about MongoDB. I am new with this and it was very helpful as
an introduction guide.


Reply
Nick Nelson 2 years ago
Would love mention of backing up MongoDB. The Comcure team would be happy to write
that article.


Reply
Wil Keenan 2 years ago
This is really helpful. Got a mongo db up and running - walked through this tutorial, in half an
hour.
I get how to modify the db from the mongo shell but.. Can you give me some quick tips on
how I can connect my simple contact manager app built on Backbone.js to my local
instance of mongo db?
Would I just be executing simple JS calls? How do I cross this divide between the simplicity
of these mongo calls and what I would actually execute from my app?


Reply
Shekhar 2 years ago
Fantastic article for beginners..


Gustavo Rod. Baldera 2 years ago
Share
Share
Share
Share
Share
Share
Share
Share
Reply
Gustavo Rod. Baldera 2 years ago
very helpful!! excellent


Reply
Michael 2 years ago
The introductory article was good. My only suggestion is to improve the English (grammar
and punctuation, specifically). ("Eats, Shoots & Leaves"? :) )


Reply
Sasikala 3 years ago
would like to see information and programming related to mapreduce on MongoDB


Reply
Justin 3 years ago
Great post. I would like to see information about JavaScript drivers for mongo in the next
post. Cheers.


Reply
Justin 3 years ago
Great post. I would like to see information about JavaScript drivers for mongo in the next
post. Cheers.


Reply
Ferry Ardhana 3 years ago
Hope this will be "MongoDB Series" :D
Great tutorial, thank you so much!


Reply
8 Gram Gorilla 3 years ago
I really need to give MongoDB a shot sometime as I've heard a lot of great things about it. I
think it would quite a hard leap for me to make conceptually though after using MySQL for
so many years. Also, are there are technical advantages to using it over MySQL? Such as
speed etc?


Reply
Sirwan Qutbi 3 years ago
What about nested data ?


Reply
Martino di Filippo 3 years ago
I'm a MongoDB noob, but wouldn't
db.nettuts.find({gender: 'm', nationality: {$in: ['english', 'american']}});
be better and easier to understand than
db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]});


Share
Share
Share
Share
Share
Share
Share
Share
Share
Reply
Reply
Parker 3 years ago
so which folder does mongoDB stores the document?


Reply
Mahesh 3 years ago
I need to get MonoDB to work with python now as i work with python most of the time. This
introductory tutorial is going to be very useful while working with mongo and python. Thanks
Matthew :)


Reply
Matthew Setter 3 years ago Mahesh
Mahesh,
great to hear. Check out: http://api.mongodb.org/python/ for more information.
Matt


Reply
Christopher 3 years ago
This method is such a throw-back for me to the days of COBOL and Data Files, where data
was stored conceptually as rows -- no columns and as such, no tables and no relations.
This is more a walk down memory lane for me. I would like to see this data storage and
retrieval type expounded upon however. The jQuery type of language syntax leads me to
evaluate MongoDB as a type of primer for beginners pursuing database theory, much the
same way that Pascal was intended as a primer to a structured approach to programming.
Having worked with relational database systems for ten years now, I cannot see much of a
serious, high data volume use case for MongoDB. But that doesn't mean I won't play with it.
Thank you for the interesting article.


Reply
dan web developer 3 years ago
looks like MongoDB is not for me since the syntax is ugly looking and annoying to type
(excessive characters like brackets, squiggly bracelets, commas and other non-letters.)


Reply
Matthew Setter 3 years ago dan web developer
Hey Dan,
you don't need to interact with it directly. There are a host of extensions (or drivers)
for it available for just about any modern, web, language. Check out:
http://www.mongodb.org/display...
Matt


Charith Saranga 3 years ago
Share
Share
Share
Share
Share
Share
Share
Teaching skills to millions worldwide.
When I try to install and run MongoDB on Windows XP, I get the following error
"Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84
exception: connect failed"
I even disabled my firewall, but the problem persist. Could anyone please tell me what could
be the reason?
Adverti sement
About
Blog
Pricing
FAQ
Support
Write For Us
Advertise
Privacy Policy
Terms of Use

2014 Envato Pty Ltd.

S-ar putea să vă placă și