Saturday, July 16, 2011

Basic quickstart commands on MongoDB

In this post I will explain the basic commands for inserting, retrieving, limiting the data sent from/to the database.

Ok so now we have inserting data to the db.

go to /bin folder and type mongo. The shell appears.
Now type insert these three documents:


> db.movies.save({title:"Harry Potter",year:2010, duration: "120 min"});
> db.movies.save({title:"Expendables",year:2010,duration:"140 min"});
> db.movies.save({title:"Green Lantern",year:2011,duration:"150 min"});


We are creating collection called movies and add three documents for movies. (Note: The data here is maybe not correct, it is just for example). So these commands corespond to the SQL statement

insert into movies (title,year,duration) values ("Harry Potter", 2010,"120 min");
insert into movies (title,year,duration) values ("Expendables", 2010,"140 min");
insert into movies (title,year,duration) values ("Green Lantern", 2011,"150 min");

 Now use this command

> db.movies.find();

This will list all documents in the movies collection. Now we will create a script with for statement.

> for (var i = 1; i <= 25; i++) db.script.save({blog:"TunePHP", j : i});
 
This script will create a collection called "script" and add documents in the format 
{blog:"TunePHP", j : i}
 
run > db.script.find(); 
 
Now the limit of the find command is 20 rows. In case where there
are more than 20 documents in a collection we use the it command. So now in terminal run
 
> it 
 
it will show the rest docs in the script collection.

No comments:

Post a Comment