Before we jump on to commands lets see some of the terminologies used.
Mongo db is bit different from our traditional RDBMS, there are no tables, rows or columns instead we will find collections and documents, looks like Object Oriented. Here collections are termed as tables, and table rows as documents. Some useful terms are
1. database holds a set of collections
2. collection holds a set of documents
3. document is a set of fields
4. field is in form of a key-value pair
5. key is a name
6. value is a any basic type like string, integer, float, timestamp, binary, etc. can be document, or array of values
Step 1 : First open command prompt and navigate to /bin/ directory and start mongo db server by issuing below command on prompt
D:\software\mongodb-win32-i386-2.6.7\bin>mongod.exe --dbpath C:/
2015-03-10T11:06:55.668+0530
2015-03-10T11:06:55.670+0530 warning: 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability.
2015-03-10T11:06:55.672+0530
2015-03-10T11:06:55.683+0530 [initandlisten] MongoDB starting : pid=2420 port=27017 dbpath=C: 32-bit host=CDP011
2015-03-10T11:06:55.684+0530 [initandlisten]
2015-03-10T11:06:55.685+0530 [initandlisten] ** NOTE: This is a 32 bit MongoDB binary.
2015-03-10T11:06:55.685+0530 [initandlisten] ** 32 bit builds are limited to less than 2GB of data (or less with --journal).
2015-03-10T11:06:55.687+0530 [initandlisten] ** Note that journaling defaults to off for 32 bit and is currently off.
2015-03-10T11:06:55.688+0530 [initandlisten] ** See http://dochub.mongodb.org/core/32bit
2015-03-10T11:06:55.690+0530 [initandlisten]
2015-03-10T11:06:55.691+0530 [initandlisten] targetMinOS: Windows XP SP3
2015-03-10T11:06:55.693+0530 [initandlisten] db version v2.6.7
2015-03-10T11:06:55.695+0530 [initandlisten] git version: a7d57ad27c382de82e9cb93bf983a80fd9ac9899
2015-03-10T11:06:55.696+0530 [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_49
2015-03-10T11:06:55.698+0530 [initandlisten] allocator: system
2015-03-10T11:06:55.699+0530 [initandlisten] options: { storage: { dbPath: "C:/"} }
2015-03-10T11:07:00.037+0530 [initandlisten] waiting for connections on port 27017
2015-03-10T11:07:19.692+0530 [initandlisten] connection accepted from 127.0.0.1:65511 #1 (1 connection now open)
2015-03-10T11:08:00.006+0530 [clientcursormon] mem (MB) res:79 virt:335
2015-03-10T11:08:00.006+0530 [clientcursormon] mapped:240
2015-03-10T11:08:00.006+0530 [clientcursormon] connections:1
Step 2 : Then Start mongo shell by executing below command
D:\software\mongodb-win32-i386-2.6.7\bin>mongo.exe
MongoDB shell version: 2.6.7
connecting to: test
Server has startup warnings:
2015-03-10T11:06:55.684+0530 [initandlisten]
2015-03-10T11:06:55.685+0530 [initandlisten] ** NOTE: This is a 32 bit MongoDB binary.
2015-03-10T11:06:55.685+0530 [initandlisten] ** 32 bit builds are limited to less than 2GB of data (or less with --journal).
2015-03-10T11:06:55.687+0530 [initandlisten] ** Note that journaling defaults to off for 32 bit and is currently off.
2015-03-10T11:06:55.688+0530 [initandlisten] ** See http://dochub.mongodb.org/core/32bit
2015-03-10T11:06:55.690+0530 [initandlisten]
Step 3 : To list all the available databases use below command
> show dbs
admin (empty)
company 0.078GB
local 0.078GB
testdb 0.078GB
Step 4 : To create and use new database
> use employee
switched to db employee
Step 5 : Now fire list all database command, to check our db is created or not.
> show dbs
admin (empty)
company 0.078GB
local 0.078GB
testdb 0.078GB
Our db 'employee' is not listed means it is not physically created yet
Step 6 : Lets insert some data. Mongo db will create database for us, when we will do some operation on it.
> db.record.save({id:"1",name:"abc"})
WriteResult({ "nInserted" : 1 })
This will create collection under our db name record having two fields id and name. Now check that database named employee created by issuing below command
> show dbs
admin (empty)
company 0.078GB
employee 0.078GB
local 0.078GB
testdb 0.078GB
We will add more documents/objects or in our database terminology records. Here we will use either document or object interchangeably.
> db.record.save({id:"2",name:"efg"})
WriteResult({ "nInserted" : 1 })
> db.record.save({id:"3",name:"xyz"})
WriteResult({ "nInserted" : 1 })
Step 7: Now we will verify that data is inserted or not by using find command. find() will list all the available documents
> db.record.find()
{ "_id" : ObjectId("54fe86e15cd2094ce66bf7d5"), "id" : "1", "name" : "abc" }
{ "_id" : ObjectId("54fe87a85cd2094ce66bf7d6"), "id" : "2", "name" : "efg" }
{ "_id" : ObjectId("54fe87b25cd2094ce66bf7d7"), "id" : "3", "name" : "xyz" }
>
We can see three document/objects listed in our collection record.
Step 8: Lets search some particular object or record just like out select statement with where clause
> db.record.find({name:"efg"})
{ "_id" : ObjectId("54fe87a85cd2094ce66bf7d6"), "id" : "2", "name" : "efg" }
>
Step 8 : Specify OR criteria using below command, this will list all objects with name equals abc or xyz.
> db.record.find({$or: [{name: 'abc'}, {name: 'xyz'}]});
{ "_id" : ObjectId("54fe86e15cd2094ce66bf7d5"), "id" : "1", "name" : "abc" }
{ "_id" : ObjectId("54fe87b25cd2094ce66bf7d7"), "id" : "3", "name" : "xyz" }
Step 9: Sort the record using sort command by specifying column or key with order -1 for desc and 1 for asc. this will sort output objects descending order.
> db.record.find().sort({name: -1});
{ "_id" : ObjectId("54fe87b25cd2094ce66bf7d7"), "id" : "3", "name" : "xyz" }
{ "_id" : ObjectId("54fe87a85cd2094ce66bf7d6"), "id" : "2", "name" : "efg" }
{ "_id" : ObjectId("54fe86e15cd2094ce66bf7d5"), "id" : "1", "name" : "abc" }
>
Step 10 : Consider a case where find() output a huge set of objects so to limit output we can use limit command as
> db.record.find().limit(2)
{ "_id" : ObjectId("54fe86e15cd2094ce66bf7d5"), "id" : "1", "name" : "abc" }
{ "_id" : ObjectId("54fe87a85cd2094ce66bf7d6"), "id" : "2", "name" : "efg" }
Step 10 : To use limit and offset use skip command along with limit, remember pagination in web page you created long back.
> db.record.find().limit(2).skip(1);
{ "_id" : ObjectId("54fe87a85cd2094ce66bf7d6"), "id" : "2", "name" : "efg" }
{ "_id" : ObjectId("54fe87b25cd2094ce66bf7d7"), "id" : "3", "name" : "xyz" }
Step 11: To update particular object, use below command. This will update object whose id is 2 to 4 and name to efgh.
> db.record.update({id:"2"},{id:"4",name:"efgh"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
as we can see 1 row affected, to check whether the update happened or not, fire
> db.record.find({id:"4"})
{ "_id" : ObjectId("54fe87a85cd2094ce66bf7d6"), "id" : "4", "name" : "efgh" }
Step 12 : To delete a object use remove method with condition.
> db.record.remove({name:"abcd"})
WriteResult({ "nRemoved" : 1 })
To verify that object is removed or not, fire list all objects using find() command
> db.record.find()
{ "_id" : ObjectId("54fe87a85cd2094ce66bf7d6"), "id" : "4", "name" : "efgh" }
{ "_id" : ObjectId("54fe87b25cd2094ce66bf7d7"), "id" : "3", "name" : "xyz" }
>
Step 13 : To remove all or truncate our collection, use remove() without any condition.
db.record.remove();
Step 14 : Join in mongo db
Please note Mongo db is non RDBMS, so it doesn't support joins but we can achieve the same using MapReduce. If you don't know what is mapreduce then google it fast before proceeding further.
first let's create two collection products with product_id and title fields and prices with product_id and price fields. So here
db.products.insert({"product_id" : 1, "title" : "Sharpie"});
db.products.insert({"product_id" : 2, "title" : "Sticky"});
db.prices.insert({"product_id" : 1, "price" : 99});
db.prices.insert({"product_id" : 2, "price" : 30});
Then we will create map functions products_map and prices_map
products_map = function() {
emit(this.product_id, {"title" : this.title});
}
prices_map = function() {
emit(this.product_id, {"price" : this.price});
};
Then create reduce function r
r = function(key, values) {
var result = {
"title" : "",
"price" : ""
};
values.forEach(function(value) {
if(value.title !== null) {result.title = value.title;}
if(value.price !== null) {result.price = value.price;}
});
return result;
}
Then execute mapReduce command with our created functions namely 'products_map' and 'prices_map' with reduce function r as below, here mapReduce is built in command which will send output in joined collection, check out syntax from mongo api doc
>
> res = db.products.mapReduce(products_map, r, {out: {reduce : 'joined'}});
{
"result" : "joined",
"timeMillis" : 515,
"counts" : {
"input" : 2,
"emit" : 2,
"reduce" : 0,
"output" : 2
},
"ok" : 1
}
> res = db.prices.mapReduce(prices_map, r, {out: {reduce : 'joined'}});
{
"result" : "joined",
"timeMillis" : 43,
"counts" : {
"input" : 2,
"emit" : 2,
"reduce" : 0,
"output" : 2
},
"ok" : 1
}
>
Now query the result in joined collection using find() command. Looks little complicated first time.
> db.joined.find()
{ "_id" : 1, "value" : { "title" : "Sharpie", "price" : 99 } }
{ "_id" : 2, "value" : { "title" : "Sticky", "price" : 30 } }
>
That's it. Congrats you now know how to start mongo db server and it's shell, and run basics commands.