MongoDB Manual
MongoDB Manual
2. To confirm the existence of database/To report the name of the current database
db
> db;
studentdb
show dbs
Note: The newly created data base is not listed in the result. The reason is that the database
needs to have at least one document to shown up in the list.
4. To drop database
db.dropDatabase();
> db.dropDatabase();
{ "ok" : 1 }
To drop the datadase first ensure that your currently placed in that database using use
command.
db.version();
> db.version();
3.2.10
db.stats();
> db.stats()
{
"db" : "test",
"collections" : 0,
"objects" : 0,
"avgObjSize" : 0,
"dataSize" : 0,
"storageSize" : 0,
"numExtents" : 0,
"indexes" : 0,
"indexSize" : 0,
"fileSize" : 0,
"ok" : 1
}
Note: Here all the details are coming Zero because i havent enter any documents and
collection in database.
7. Help command
db.help();
show collections
2. Create collection
> db.createCollection("Person");
{ "ok" : 1 }
3. To drop collection
> db.Person.drop();
true
Inserting Documents:
1. db.student.insert({_id:1,Name:"xxx",GPA:"9.5",Hobbies:"surfing"});
WriteResult({ "nInserted" : 1 })
db.student.insert({Name:"ZZZ",GPA:"7.5",Hobbies:"chess"});
WriteResult({ "nInserted" : 1 })
> db.student.find();
db.collectionname.find();
db.student.find();
db.collectionname.find().pretty();
Inserting 2 documents
db.student.insert({_id:1,Name:"xxx",GPA:"9.5",Hobbies:"surfing"});
db.student.insert({_id:1,Name:"xxx",GPA:"9.5",Hobbies:"surfing"});
db.student.find().pretty();
{ "_id" : 1, "Name" : "xxx", "GPA" : "9.5", "Hobbies" : "surfing" }
{ "_id" : 2, "Name" : "YYY", "GPA" : "8.5", "Hobbies" : "cricket" }
4. Update Method
Update method it checks whether the document with id is already exists is so it will
update the required field otherwise it will insert a new document with new id.
Here UPSERT method is very imporant:
If UPSERT =false (default value) then new record are not inserted
If UPSERT =true then new records are inserted
when using Update method its required to use $set operator to update the fields
suppose i will try to update the document with ID3 it is not there in the collection
student.
db.student.update({_id:3,Name:"FFF",GPA:"6.5"},{$set:{Hobbies:"reading"}},
{upsert:true});
here id 3 document is not there so it will try to insert the new document with id:3
db.student.find({_id:3});
Here you can Note Find method . That is conditions can be applied in find method
Now we will try to update the alreday existing document with new data
db.student.update({_id:3},{$set:{Hobbies:"listening music"}},{upsert:true});
db.student.find({_id:3});
db.student.find();
> db.student.find();
db.student.update({_id:4, Name:"GGG",GPA:"7.5"},{$set:{Hobbies:"playing
games",location:"india"}},{upsert:true});
> db.student.find();
{ "_id" : 1, "Name" : "xxx", "GPA" : "9.5", "Hobbies" : "surfing" }
{ "_id" : 2, "Name" : "YYY", "GPA" : "8.5", "Hobbies" : "cricket" }
{ "_id" : ObjectId("580eff3d9e9cce5d45a2af1b"), "Name" : "ZZZ", "GPA" : "7.5", "Hobbies" :
"chess" }
{ "_id" : 3, "GPA" : "6.5", "Name" : "FFF", "Hobbies" : "listening music" }
{ "_id" : 4, "GPA" : "7.5", "Name" : "GGG", "Hobbies" : "playing games", "location" : "india" }
5. Save method
save method will insert a new document if the document with the specified _id does not exist.
If adocument with the specified id exists it replaces the existing document with new one.
Now i am saving the document with id :5 this is not in collection so save method creates new one.
db.student.save({_id:5, Name:"jjj",GPA:"8.0"});
db.student.find();
{ "_id" : 1, "Name" : "xxx", "GPA" : "9.5", "Hobbies" : "surfing" }
{ "_id" : 2, "Name" : "YYY", "GPA" : "8.5", "Hobbies" : "cricket" }
{ "_id" : ObjectId("580eff3d9e9cce5d45a2af1b"), "Name" : "ZZZ", "GPA" : "7.5", "Hobbies" :
"chess" }
{ "_id" : 3, "GPA" : "6.5", "Name" : "FFF", "Hobbies" : "listening music" }
{ "_id" : 4, "GPA" : "7.5", "Name" : "GGG", "Hobbies" : "playing games", "location" : "india" }
{ "_id" : 5, "Name" : "jjj", "GPA" : "8.0"}
db.student.save({_id:5,Name:"jjj",GPA:"7.5",Hobbies:"cricket"});
db.student.find();
6. Removing a document
db.student.remove({_id:3});
WriteResult({ "nRemoved" : 1 })
db.student.find();
For example we are trying to remove the field gpa from a document using update and with
unset method
db.student.update({_id:5},{$unset:{GPA:"7.5"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find();
{ "_id" : ObjectId("580f2464e32bbc76b4975e17"), "Name" : "ZZZ", "GPA" : "7.5", "Hobbies" :
"chess" }
{ "_id" : 4, "Name" : "jjj", "GPA" : "8.0" }
{ "_id" : 5, "Name" : "jjj", "Hobbies" : "cricket" }
Searching A document baed on condition with Find () method
db.student.find({_id:4});
db.student.find({Hobbies:"cricket"});
db.student.find({Name:"ZZZ",GPA:"7.5"});
db.student.find({},{Name:"ZZZ",GPA:"7.5",_id:0});
{ "Name" : "Abilash" }
{ "Name" : "Babu" }
{ "Name" : "Chithra" }
{ "Name" : "sindhu" }
{ "Name" : "Manu" }
{ "Name" : "Dinesh" }
{ "Name" : "sheela" }
{ "Name" : "vignesh" }
{ "Name" : "Kala" }
{ "Name" : "Kiran" }
db.RankList.find({},{Name:1,GPA:1,_id:0});
{ "Name" : "Abilash", "GPA" : "6.5" }
{ "Name" : "Babu", "GPA" : "8.5" }
{ "Name" : "Chithra", "GPA" : "7.5" }
{ "Name" : "sindhu", "GPA" : "7.9" }
{ "Name" : "Manu", "GPA" : "9.9" }
{ "Name" : "Dinesh", "GPA" : "5.9" }
{ "Name" : "sheela", "GPA" : "6.7" }
{ "Name" : "vignesh", "GPA" : "7.7" }
{ "Name" : "Kala", "GPA" : "8.1" }
{ "Name" : "Kiran", "GPA" : "8.8" }
>
Conditional operators
db.RankList.find({GPA:{$gt:"6.7"}});
db.RankList.find({GPA:{$ne:"6.7"}});
db.student.find({Hobbies:{$in:['chess','surfing']}});
db.student.find({Hobbies:{$nin:['chess','surfing']}});
Name Description
$eq Matches values that are equal to a specified value.
$gt Matches values that are greater than a specified value.
$gte Matches values that are greater than or equal to a specified value.
$lt Matches values that are less than a specified value.
$lte Matches values that are less than or equal to a specified value.
$ne Matches all values that are not equal to a specified value.
$in Matches any of the values specified in an array.
$nin Matches none of the values specified in an array.
String Operations
db.student.find({Name:/^y/});
Or
db.student.find({Name:{$regex:"^y"}});
db.student.find({Hobbies :/t$/});
or
db.student.find({Hobbies :{$regex:"t$"}});
3. To find the document where the hobbies has an “s” in any postion
db.student.find({Hobbies:/s/});
db.student.find({Hobbies:/.*s.*/});
db.student.find({Hobbies:{$regex:"s"}});
Dealing with Null values;
A Null is a missing or unknown value. When we place aNULL value for afield ,it implies that
currently we do not know the value or the value is missing.
We will try to insert the new field location with NULL value in document 3
db.student. find({$or:[{_id:2},{_id:3}]});
db.student.find({Location:{$eq:null}});
db.student.update({_id:3},{$unset:{Loaction:null}});
Count:
db.student.count();
db.student.count({Hobbies:"chess"});
2
Limit
db.student.find().limit(2);
db.student.find({Hobbies:"chess"}).limit(1);
Sort
To sort the documents in ascending or descending order.
db.student.find().sort({Name:1});
db.student.find().sort({Name:-1});
Skip
To skip first particular number of documents
db.student.find().skip(2);
db.student.find().skip(1).sort({Name:1});
db.student.find().skip(db.student.count()-2);
db.student.find().skip(1).limit(3);
Arrays
To create a collection by the name “Food”. Ecah documents have fruits array
db.createCollection("Food");
2.Inserting values
db.Food.insert({_id:1,fruits:['banana','apple','cherry']});
WriteResult({ "nInserted" : 1 })
> db.Food.insert({_id:2,fruits:['orange','butterfruit','mango']});
WriteResult({ "nInserted" : 1 })
> db.Food.insert({_id:3,fruits:['pineapple','strawberry','grapes']});
WriteResult({ "nInserted" : 1 })
> db.Food.insert({_id:4,fruits:['banana','strawberry','grapes']});
WriteResult({ "nInserted" : 1 })
> db.Food.insert({_id:5,fruits:['orange','grapes']});
WriteResult({ "nInserted" : 1 })
3. To display
db.Food.find();
db.Food.find({fruits:'banana'});
3. To find documents those have the fruits array having”garpes” in the first index postion
4.To find documents those have the fruits array having”garpes” in the second index postion
db.Food.find({'fruits.2':'grapes'});
5. size of array (to find the document having the fruit arry size as 2)
db.Food.find({"fruits":{$size:2}});
6. To display the first two elemnts of the array from document 1 using Slice
db.Food.find({_id:1},{"fruits":{$slice:2}});
7. To find documents which have elements”orange” and “grapes” in the array fruit.($all)
db.Food.find({fruits:{$all:["orange","grapes"]}});
8. To dipslay only two elements from the arry starting with 0 th index poistion from document1
db.Food.find({_id:1},{"fruits":{$slice:[0,2]}});
9. To dipslay only two elements from the arry starting with 1 st index poistion from document1
db.Food.find({_id:1},{"fruits":{$slice:[1,2]}});
Update on arrays
db.Food.update({_id:4},{$set:{'fruits.1':'apple'}});
2. To updtae the document id:1 and replace the element “apple “ with “An apple”
db.Food.update({_id:1,'fruits':'apple'},{$set:{'fruits.$':'An apple'}});
3. To upadte the document with _id:2 and push a new key value pair in the fruit array
db.Food.update({_id:2},{$push:{price:{orange:60,butterfruit:200,mango:120}}});
db.Food.find({_id:2});
db.Food.update({_id:4},{$addToSet:{fruits:"orange"}});
db.food.update({_id:4},{$pop:{fruits:1}});
db.food.update({_id:4},{$pop:{fruits:-1}});
Aggregate functions
1. creating a collection “customer”
db.createCollection("customer");
2. Inserting values
db.customer.insert([{Custid:"C123",AccBal:500,AccType:"S"},
{Custid:"C123",AccBal:900,AccType:"S"},{Custid:"C111",AccBal:1200,AccType:"S"},
{Custid:"C123",AccBal:1500,AccType:"C"}]);
3. to display
db.customer.find();
db.customer.aggregate({$group:{_id:"$Custid",TotBal:{$sum:"$AccBal"}}});
5. To filter on AccType:”S” and then groupit based on Custid and then compute sum of Accbal .
db.customer.aggregate({$match:{AccType:"S"}},{$group:{_id:"$Custid",TotBal:
{$sum:"$AccBal"}}});
6.To filter on AccType:”S” and then groupit based on Custid and then compute sum of Accbal and
filter those documents where in the “TotBal” is graeter than 1200.
db.customer.aggregate({$match:{AccType:"S"}},{$group:{_id:"$Custid",TotBal:
{$sum:"$AccBal"}}},{$match:{TotBal:{$gt:1200}}});
db.customer.aggregate({$group:{_id:"$Custid",TotBal:{$avg:"$AccBal"}}});
8. To group id and determine the amx and min accbal for each type;
db.customer.aggregate({$group:{_id:"$Custid",TotBal:{$max:"$AccBal"}}});
{ "_id" : "C111", "TotBal" : 1200 }
{ "_id" : "C123", "TotBal" : 1500 }
> db.customer.aggregate({$group:{_id:"$Custid",TotBal:{$min:"$AccBal"}}});
{ "_id" : "C111", "TotBal" : 1200 }
{ "_id" : "C123", "TotBal" : 500 }
>
MapReduce
1. map function
2. reduce function
3. To execute mapreduce
db.customer.mapReduce(map,reduce,{out:"CustomerTotal",query:{AccType:"S"}});
{
"result" : "CustomerTotal",
"timeMillis" : 436,
"counts" : {
"input" : 3,
"emit" : 3,
"reduce" : 1,
"output" : 2
},
"ok" : 1
}
db.CustomerTotal.find();
> db.system.js.find();
when you execute this command it displays the prompt only it means there is no js program in
machine.
2. To add java script programming for factorial
WriteResult({ "nInserted" : 1 })
db.system.js.find();
{ "_id" : "fact", "value" : function (n) {if(n==1) return 1; else return n*fact(n-1);} }
> db.eval("fact(3)");
Cursors in MongoDB
1. create a collection Alphabets
> db.createCollection("Alphabets");
{ "ok" : 1 }
db.Alphabets.insert({_id:1,alpha:"a"});
WriteResult({ "nInserted" : 1 })
db.Alphabets.insert({_id:2,alpha:"b"});
WriteResult({ "nInserted" : 1 })
> db.Alphabets.insert({_id:3,alpha:"c"});
WriteResult({ "nInserted" : 1 })
> db.Alphabets.insert({_id:4,alpha:"d"});
WriteResult({ "nInserted" : 1 })
> db.Alphabets.insert({_id:5,alpha:"e"});
WriteResult({ "nInserted" : 1 })
> db.Alphabets.find();
When using cursor it iterates the read opeartion upto 20 documents by default.
3. Creating a cursor
Manual cursors:
the alphabet is :a
the alphabet is :b
the alphabet is :c
the alphabet is :d
the alphabet is :e
> db.createCollection("books");
{ "ok" : 1 }
2. Inserting Documents
3. Displaying documents
> db.books.find().pretty();
{
"_id" : 6,
"Type" : "ML",
"BName" : "ML for Hackers",
"Qty" : 25,
"price" : 400
}
{
"_id" : 7,
"Type" : "webmining",
"BName" : "Mining social data",
"Qty" : 15,
"price" : 500
}
{
"_id" : 8,
"Type" : "Programming",
"BName" : "Python for data analysis",
"Qty" : 25,
"price" : 700
}
{
"_id" : 9,
"Type" : "Visualization",
"BName" : "Visualizing Data",
"Qty" : 25,
"price" : 200
}
{
"_id" : 10,
"Type" : "ML",
"BName" : "ML for Bigdata",
"Qty" : 25,
"price" : 600
}
4. Creating an index for “Type” field in the books collection using ensureIndex method
> db.books.ensureIndex({"Type":1});
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.books.stats();
{ "ns" : "cursorexample.books",
"count" : 5,
"size" : 468,
"avgObjSize" : 93,
"storageSize" : 36864,
"capped" : false,
"wiredTiger" : {
"metadata" : {
"formatVersion" : 1
},
.................... },
"nindexes" : 2,
"totalIndexSize" : 53248,
"indexSizes" : {
"_id_" : 36864,
"Type_1" : 16384
},
"ok" : 1
}
6. Get the list of all indexes on the books collection using getIndexes() method
> db.books.getIndexes();
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "cursorexample.books"
},
{
"v" : 1,
"key" : {
"Type" : 1
},
"name" : "Type_1",
"ns" : "cursorexample.books"
}
]
> db.books.find({"Type":"ML"}).pretty().hint({"Type":1});
{
"_id" : 6,
"Type" : "ML",
"BName" : "ML for Hackers",
"Qty" : 25,
"price" : 400
}
{
"_id" : 10,
"Type" : "ML",
"BName" : "ML for Bigdata",
"Qty" : 25,
"price" : 600
}
> db.books.find({"Type":"ML"}).pretty().hint({"Type":1}).explain();
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "cursorexample.books",
"indexFilterSet" : false,
"parsedQuery" : {
"Type" : {
"$eq" : "ML"
}
},
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"Type" : 1
},
"indexName" : "Type_1",
"isMultiKey" : false,
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 1,
"direction" : "forward",
"indexBounds" : {
"Type" : [
"[\"ML\", \"ML\"]"
]
}
}
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "200809JUNC0287-A",
"port" : 27017,
"version" : "3.2.10",
"gitVersion" : "79d9b3ab5ce20f51c272b4411202710a082d0317"
},
"ok" : 1
}
_id,FName,LName
1,Anith,Devaraj
2,Dipak,Jena
3,Senthil,Prabhu
4,Vidya,Muthusamy
5,Arvind,Palaniappan
Start mongo DB
> db.things.find();
{ "_id" : 2, "FName" : "Dipak", "LName" : "Jena" }
{ "_id" : 3, "FName" : "Senthil", "LName" : "Prabhu" }
{ "_id" : 4, "FName" : "Vidya", "LName" : "Muthusamy" }
{ "_id" : 5, "FName" : "Arvind", "LName" : "Palaniappan" }
{ "_id" : 1, "FName" : "Anith", "LName" : "Devaraj" }
>
MongoExport
> db.things.find();
{ "_id" : 2, "FName" : "Dipak", "LName" : "Jena" }
{ "_id" : 3, "FName" : "Senthil", "LName" : "Prabhu" }
{ "_id" : 4, "FName" : "Vidya", "LName" : "Muthusamy" }
{ "_id" : 5, "FName" : "Arvind", "LName" : "Palaniappan" }
{ "_id" : 1, "FName" : "Anith", "LName" : "Devaraj" }
In command prompt
To confirm
Cat output.csv
Note:
-d : database name
-c : Collection name
-type: file type
-f: Fields
-o output