Main Tutorials

MongoDB hello world example

mongodb hello world

A quick guide to show you how to do basic operations like create, update, find, delete record and indexing in MongoDB. This example is using MongoDB 2.0.7, running on Mac OS X 10.8, both MongoDB client and server console are run on localhost, same machine.

1. Install MongoDB

Install MongoDB on Windows, Ubuntu or Mac OS X. The installation is easy, basically just download the MongoDB zip file, extra and run the command – $MongoDB-folder/bin/mongod.

Uses mongod to start MongoDB.


$./mongod
Tue Sep 11 21:55:36 [initandlisten] MongoDB starting : 
pid=72280 port=27017 dbpath=/data/db/ 64-bit host=Yongs-MacBook-Air.local
Tue Sep 11 21:55:36 [initandlisten] db version v2.0.7, pdfile version 4.5
Tue Sep 11 21:55:36 [initandlisten] options: {}
Tue Sep 11 21:55:36 [initandlisten] journal dir=/data/db/journal
Tue Sep 11 21:55:36 [initandlisten] recover : no journal files present, no recovery needed
Tue Sep 11 21:55:36 [websvr] admin web console waiting for connections on port 28017
Tue Sep 11 21:55:36 [initandlisten] waiting for connections on port 27017

2. Connect MongoDB

To connect MongoDB, uses $MongoDB-folder/bin/mongo


$ ./mongo
MongoDB shell version: 2.0.7
connecting to: test

3. Create a database or table (collection)

In MongoDB, both database and table are created automatically when the first time data is inserted. Uses use database-name, to switch to your database (even this is not created yet).

In below example, after you inserted a single record, database “mkyong”, and table “users” are created on the fly.


$ ./mongo
MongoDB shell version: 2.0.7
connecting to: test
> use mkyong
switched to db mkyong

> db.users.insert({username:"mkyong",password:"123456"})
> db.users.find()
{ "_id" : ObjectId("504f45cd17f6c778042c3c07"), "username" : "mkyong", "password" : "123456" }

Three database commands you should know.

  1. show dbs – List all databases.
  2. use db_name – Switches to db_name.
  3. show collections – List all tables in the current selected database.
Note
In MongoDB, collection means table in SQL.

4. Insert A Record

To insert a record, uses db.tablename.insert({data}) or db.tablename.save({data}), both works, no idea why MongoDB created both.


> db.users.save({username:"google",password:"google123"})
> db.users.find()
{ "_id" : ObjectId("504f45cd17f6c778042c3c07"), "username" : "mkyong", "password" : "123456" }
{ "_id" : ObjectId("504f48ea17f6c778042c3c0a"), "username" : "google", "password" : "google123" }

5. Update A Record

To update a record, uses db.tablename.update({criteria},{$set: {new value}}). In below example, the password of username : “mkyong” is updated.


> db.users.update({username:"mkyong"},{$set:{password:"hello123"}})
> db.users.find()
{ "_id" : ObjectId("504f48ea17f6c778042c3c0a"), "username" : "google", "password" : "google123" }
{ "_id" : ObjectId("504f45cd17f6c778042c3c07"), "password" : "hello123", "username" : "mkyong" } 

6. Find Records

To find or query records, uses db.tablename.find({criteria}).

6.1 List all records from table “users”.


> db.users.find()
{ "_id" : ObjectId("504f48ea17f6c778042c3c0a"), "username" : "google", "password" : "google123" }
{ "_id" : ObjectId("504f45cd17f6c778042c3c07"), "password" : "hello123", "username" : "mkyong" } 

6.2 Find records where username is “google”


> db.users.find({username:"google"})
{ "_id" : ObjectId("504f48ea17f6c778042c3c0a"), "username" : "google", "password" : "google123" }

6.3 Find records where username’s length is less than or equal to 2


db.users.find({$where:"this.username.length<=2"})

6.4 Find records where username field is existed.


db.users.find({username:{$exists : true}})

7. Delete Record

To delete a record, uses db.tablename.remove({criteria}). In below example, the record of username “google” is deleted.


> db.users.remove({username:"google"})
> db.users.find()
{ "_id" : ObjectId("504f45cd17f6c778042c3c07"), "password" : "hello123", "username" : "mkyong" }
Note
To delete all records from a table, uses db.tablename.remove().
To drop the table, uses db.tablename.drop().

8. Indexing

Index may help you increase the speed of querying data.

8.1 List all indexes of table “users”, by default the column “_id” is always the primary key and created automatically.


> db.users.getIndexes()
[
	{
		"v" : 1,
		"key" : {
			"_id" : 1
		},
		"ns" : "mkyong.users",
		"name" : "_id_"
	}
]
>

8.2 To create an index, uses db.tablename.ensureIndex(column). In below example, an index is created on column “username”.


> db.users.ensureIndex({username:1})
> db.users.getIndexes()
[
	{
		"v" : 1,
		"key" : {
			"_id" : 1
		},
		"ns" : "mkyong.users",
		"name" : "_id_"
	},
	{
		"v" : 1,
		"key" : {
			"username" : 1
		},
		"ns" : "mkyong.users",
		"name" : "username_1"
	}
]

8.3 To drop an index, uses db.tablename.dropIndex(column). In below example, the index on column “username” is deleted or dropped.


> db.users.dropIndex({username:1})
{ "nIndexesWas" : 2, "ok" : 1 }
> db.users.getIndexes()
[
	{
		"v" : 1,
		"key" : {
			"_id" : 1
		},
		"ns" : "mkyong.users",
		"name" : "_id_"
	}
]
>

8.4 To create an unique index, uses db.tablename.ensureIndex({column},{unique:true}). In below example, an unique index is created on column “username”.


> db.users.ensureIndex({username:1},{unique:true});
> db.users.getIndexes()
[
	{
		"v" : 1,
		"key" : {
			"_id" : 1
		},
		"ns" : "mkyong.users",
		"name" : "_id_"
	},
	{
		"v" : 1,
		"key" : {
			"username" : 1
		},
		"unique" : true,
		"ns" : "mkyong.users",
		"name" : "username_1"
	}
]

10. Help

At last, uses help() to guide you how to do things in MongoDB.

10.1 help – All available commands.


> help
	db.help()                    help on db methods
	db.mycoll.help()             help on collection methods
	rs.help()                    help on replica set methods
	help admin                   administrative help
	help connect                 connecting to a db help
	help keys                    key shortcuts  
	//...                    

10.2 db.help() – Shows help on db.


> db.help()
DB methods:
	db.addUser(username, password[, readOnly=false])
	db.auth(username, password)
	db.cloneDatabase(fromhost)
	db.commandHelp(name) returns the help for the command
	db.copyDatabase(fromdb, todb, fromhost)
	//...

10.3 db.collection.help() – Shows help on collection (table).


> db.users.help()
DBCollection help
	db.users.find().help() - show DBCursor help
	db.users.count()
	db.users.dataSize()
	db.users.distinct( key ) - eg. db.users.distinct( 'x' )
	db.users.drop() drop the collection
	db.users.dropIndex(name)
	//...

10.4 db.collection.function.help() – Shows help on function.


> db.users.find().help()
find() modifiers
	.sort( {...} )
	.limit( n )
	.skip( n )
	.count() - total # of objects matching query, ignores skip,limit
	.size() - total # of objects cursor would return, honors skip,limit
	.explain([verbose])
    //...

Done. Hope this summary of MongoDB commands could help others.

References

  1. Official MongoDB tutorials
  2. MongoDB Indexes

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
12 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Xuebin Zhao
11 years ago

ABOUT “To insert a record, uses db.tablename.insert({data}) or db.tablename.save({data}), both works, no idea why MongoDB created both.”

PLEASE REFER TO http://stackoverflow.com/questions/7612703/difference-between-db-collectionx-save-and-db-collectionx-insert

Anton
6 years ago
Reply to  Xuebin Zhao

It’is like a difference between REPLACE and INSERT in SQL DB

Jay Kasundra
7 years ago
Reply to  Xuebin Zhao

Its good to know this. Thank you.

carlos rodriguez
11 years ago

I have a question, by default always appear “[websvr] admin web console waiting for connections on port XXXX”? there is no way to remove it?

THURMAN SANDERS
3 years ago

Terrific stuff as usual…thanks..for all of your simple but helpful tutorials!

alleni123
10 years ago

Those tutorials will definitely help me out during my career. Thanks so much.

Shivam Maharshi
10 years ago

Thanks a lot for your tutorials. You are awesome !!

Subramanyam
11 years ago

Thanks alot sir your tutorials are really helpful for a beginner like me 🙂

regards,
Subramanyam

Sankara Yadavalli
11 years ago

Thanks alot mkyong. It’s really good for quick start up. I really appreciate your hard work for building up with good examples and sample code.

thanks,
Sankara.

jim northrop
11 years ago

have been exploring the cloud foundry offerings and thought i’d start with mongoDB. My tool of choice is groovy (JVM) and like to keep things simple until i understand the technology. So i avoid using eclipse, springsource at the start until the lightbulb comes on 🙂

this post has been just what i needed to get going with mongo. i can adjust it for groovy syntax and it will sure speed up my efforts. So i just wanted to say a BIG ‘Thank you’ for this work. It’s just what the doctor ordered !!!

Now will try to adapt your sample to run in a cloud foundry remote instance. 😀

kind regards
jim

Varshu
11 years ago

Your examples are good. What is the real benefit of using mongo db?

carlos rodriguez
11 years ago
Reply to  Varshu

compared to SQL is much faster when the consultations show, and you can store much more data in a single BSON unrelated, unless you use DBRef, is unstructured, you can save as you want …