Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 16

########################################################################

########### CRUD OPERATIONS ##########


########################################################################
---Creating Database & Inserting Records

db.tecnotree.insert({
first: 'judi',
last: 'dench',
dob: '09/12/1934',
gender: 'f',
hair_colour: 'white',
occupation: 'actress',
nationality: 'english'
});

---Inserting Records

db.hellos.insert({
a: "hello, world!"
})

var test={
a: "hello, world!"
}
db.hellos.save(test)

db.hellos.copyTo('hellos1');
db.hellos1.find().pretty()

var test=db.hellos.findOne({

},
{
_id: 0
})
db.hellos1.save(test);
db.hellos1.find().pretty()

----Inserting Record : Array , Sub Docs

db.hellos.insert({
a: [
"red",
"green",
"blue"
]
});

db.hellos.insert({
Name: "Balaji",
Fav_Colours: [
"red",
"green",
"blue"
],
"Address": {
BuildingNo: "A-2/3",
"Address1": "Bada Mansion",
City: "Mumbai",
State: "Maharashtra"
}
})

db.hellos.find().pretty()

----ObjectId

ObjectId("554b516a7d533c50dd491be1").getTimestamp()

var mydate2 = ISODate()


mydate2

---Common Errors : Insert Statement

db.hellos.insert( { _id : [ 1, 2, 3 ] } )

db.hellos.insert( { _id : 3 } )
db.hellos.insert( { _id : 3 } )
db.hellos.insert( { "Hello" } )

----ordered bulk inserts

db.things.insert([
{
_id: 19,
type: "atom",
symbol: "K"
},
{
_id: 20,
type: "car",
color: "red"
},
{
_id: 20,
type: "planet",
name: "Saturn"
},
{
type: "office",
street: "229 West 43rd Street, 5th Floor",
city: "New York",
state: "NY"
}
])

db.things.find().pretty();
db.things.find().forEach(printJson)

----UnOrdered BULK Insert

db.otherThings.insert([
{
_id: 19,
type: "atom",
symbol: "K"
},
{
_id: 20,
type: "car",
color: "red"
},
{
_id: 20,
type: "planet",
name: "Saturn"
},
{
type: "office",
street: "229 West 43rd Street, 5th Floor",
city: "New York",
state: "NY"
}
],
{
ordered: false
})

db.otherThings.find().pretty();

----Creating test data in the shell

for(i=1;i<=10000;i++){
db.stuff.insert({
"a": i
})
}

db.stuff.find()

----CURSOR

---To Set Batch size in mongo shell

DBQuery.shellBatchSize=10

---Implicit Cursor
db.testcol.drop();

for(i=1;i<=10000;i++){
db.testcol.insert({
a: Math.floor(Math.random()*100+1),
b: Math.floor(Math.random()*100+1)
})
}

db.testcol.find()
it

----Explicit Cursor
var x = db.testcol.find()
x.next()
x.hasNext()
y = x.next()
y.a
x
db.runCommand({cursorInfo:1}) /****Depricated*****/
var test=db.serverStatus()
test.metrics.cursor
test.cursors

---Query Interface

db.users.find( { age: { $gt: 18 } }, { name: 1, address: 1 } ).limit(5)

---Read Queries

db.users.find()
db.users.find().forEach(printjson)
db.users.find().pretty()

a=db.links.findOne()
b=db.links.find().pretty()
var b=db.links.find().pretty()

db.links.find({favorites: 100}, {title:1, url: true}).pretty()


db.links.find({favorites: 100}, {title:0}).pretty()

var john = db.users.findOne({'name.first': 'John'}).pretty();


db.links.find({userId: john._id}, {title: 1, _id: 0}).pretty();
db.links.find({userId: john._id}, {title: 1,userId:0, _id: 0}).pretty();

db.links.find({}, {title: 1, favorites: 1, _id: 0}).sort({favorites:1});


//Query to verify the <> results
--QUERY USING GREATER THAN �>�
db.links.find({favorites: {$gt: 150}}, {title: 1, favorites: 1, _id: 0});

--Query using Less than �<�


db.links.find({favorites: {$lt: 150}}, {title: 1, favorites: 1, _id: 0});

---Verifying the above Queries


db.links.find({favorites: {$gt: 150}}, {title: 1, favorites: 1, _id:
0}).count();
db.links.find({favorites: {$lt: 150}}, {title: 1, favorites: 1, _id:
0}).count();
db.links.count()

--QUERY USING GREATER THAN EQUAL TO �>=�


db.links.find({favorites: {$gte: 100}}, {title: 1, favorites: 1, _id: 0});

--QUERY USING LESS THAN EQUAL TO �<=�


db.links.find({favorites: {$lte: 100}}, {title: 1, favorites: 1, _id: 0});

--QUERY USING LESS THAN AND GREATER THAN COMBINATION �< >�
db.links.find({favorites: {$gt: 100,$lt:300}}, {title: 1, favorites: 1, _id:
0});

--QUERY USING LESS THAN EQUAL TO AND GREATER THAN EQUAL TO COMBINATION �<=
>=� OR �BETWEEN AND�
db.links.find({favorites: {$gte: 100,$lte:300}}, {title: 1, favorites: 1,
_id: 0});

--QUERY FOR IN RANGES


db.users.find({'name.first': {$in: ['John', 'Jane'] }});
--SELECTING JOHN AND JANE WITH PROJECTION "NAME.FIRST"
db.users.find({'name.first': {$in: ['John', 'Jane'] }}, {'name.first':
1});

--SELECTING OTHER THAN JOHN AND JANE WITH PROJECTION "NAME.FIRST"


db.users.find({'name.first': {$nin: ['John', 'Jane'] }}, {'name.first':
1});

--Using IN for Array any matched criteria


db.links.find({}, {title: 1, tags:1, _id: 0}); //Query to Verify
db.links.find({tags: {$in: ['marketplace','code']}}, {title: 1, tags:1, _id:
0});

--All matched criteria for Array


db.links.find({tags: {$all: ['marketplace','code']}}, {title: 1, tags:1, _id:
0});

--Query using not equal operator �<> !=�


db.links.find({tags: {$ne: 'code'}}, {title: 1, tags:1});

--Query using not equal operator �<> !=� for Array


db.links.find({tags: {$ne: ['code']}}, {title: 1, tags:1});
db.links.find({tags: {$ne: [ "tutorials", "dev", "code"]}}, {title: 1,
tags:1});

--Query using OR operator


db.users.find({$or: [{'name.first': 'John'}, {'name.last': 'Wilson'}]},
{name: 1});

--Query using NOR operator


db.users.find({$nor: [{'name.first': 'John'}, {'name.last': 'Wilson'}]},
{name: 1});

---Query using AND Operator


db.users.find({$and: [{'name.first': 'Bob'}, {'name.last': 'Smith'}]},
{'name.first': 1,'name.last': 1,_id:0});
----Query using EXISTS operator (To check the field exists)
db.users.find({email: {$exists: true}}, {name:1, email:1,_id:0});

----Query using NOT EXISTS operator (To check the field exists)
db.users.insert({
"name" : {
"first" : "Arun",
"last" : "Bhat"
},
"age" : 39,
"passwordHash" : "last_password_hash",
"logins" : [
{
"at" : ISODate(),
"minutes" : 59
},
{
"at" : ISODate(),
"minutes" : 20
}
]
});
db.users.find({email: {$exists: false}}, {name:1, email:1,_id:0});

---Query using MOD operator


db.links.find({favorites: {$mod: [5, 0]}}, {title:1, favorites:1, _id:0});

---Query using NOT operator


db.links.find({favorites: {$not: {$mod: [5, 0]}}}, {title:1, favorites:1,
_id:0});

---Query using elemMatch operator (For array of embedded documents)


db.users.find({ logins: {$elemMatch: {minutes: 20} } },{logins:1,_id:0});
db.users.find({ logins: {$elemMatch: {at : { $lt: new Date(2012, 3,
30) }}}});
db.users.find({"logins.minutes": 20 },{logins:1,_id:0}).pretty();

--Query using $where Operator (Matches documents that satisfy a JavaScript


expression.)
db.users.find({ $where: "this.name.first == 'John'"});
db.users.find({ $where: 'this.name.first == "John"'});
db.users.find({ $where: "this.name.first == 'John'", age: 30});
shortcuts for using where ONLY
db.users.find( 'this.name.first == "John"' );
var f = function() {return this.name.first === 'John'}
db.users.find(f);
db.users.find({ $where: f });

---DISTINCT Query
db.links.distinct('favorites');
db.links.distinct('url');

---COUNT Query
db.users.find({'name.first' : 'John'}).count();
db.users.count({'name.first' : 'John'});
db.users.count();

---Query using skip and limit


db.links.find({}, {title: 1, _id: 0}).skip(3).limit(3);

--Query using Regex operator


db.links.find({title: {$regex: /tuts\+$/, $ne: 'Mobiletuts+' }}, {title: 1});
db.links.find({title: /tuts\+$/ }, {title: 1});

--Query to Execute before sorting: db.links.find({}, {title: 1, _id: 0});

--Sorting ASC order


db.links.find({}, {title: 1, _id: 0}).sort({title: 1});

--Sorting DESC order


db.links.find({}, {title: 1, _id: 0}).sort({title: -1});
db.links.find({}, {title: 1, favorites: 1, _id: 0}).sort({favorites: -1,
title: 1});

--Finding MAX using sort and limit


db.links.find({}, {title: 1, favorites: 1, _id: 0}).sort({favorites:
-1}).limit(1)

--Finding MIN using sort and limit


db.links.find({}, {title: 1, favorites: 1, _id: 0}).sort({favorites:
1}).limit(1)

---To Find documents like row


db.users.find({},
{ 'name.first' : 1,
'name.last' : 1,
'email' : 1
}
).forEach( function(x) { print(x.name.first,x.name.last,x.email);});

--Update Queries

---Update by replacement
db.users.update({'name.first': 'John'}, { job: 'developer'});

--Upsert
---Following statement will fail silently
db.users.update({name: 'Kate Wills'}, {name: 'Kate Wills', job: 'Lisp
Developer'});
db.users.find({name: 'Kate Wills'});
--Following Upsert statement will insert a record
db.users.update({name: 'Kate Wills'}, {name: 'Kate Wills', job:
'Lisp Developer'}, true);
Update using fetching values into Variable
var n = { title: 'Nettuts+'};
db.links.find(n);
db.links.update(n, {$inc: {favorites: 5}});
db.links.find(n);
var q = {name: 'Kate Wills'};
db.users.find(q);
db.users.update(q, {$set: {job: 'Web Developer'}});
db.users.update(q, {$set: {email: 'kw@gmail.com'}});
db.users.update(q, {$unset: {job: 'Web Dev'}});
db.links.find({}, {title: 1, favorites: 1, _id: 0}).sort({favorites: -1,
title: 1});

--Update Globally
db.users.insert({name: {first: 'Jane'}});
db.users.find({'name.first':'Jane'});

--This will only update the first match record


db.users.update({ 'name.first': 'Jane' }, {$set: {Job: 'Web developer'}});

--This will update all matched records


db.users.update({ 'name.first': 'Jane' }, {$set: {Job: 'Web developer'}},
false, true);

--Save method
var bob = db.users.findOne({ 'name.first': 'Bob'});
bob.job = 'Server Admin';
db.users.save(bob);
db.users.find({ 'name.first': 'Bob'});

--FindAndModify
db.users.findAndModify({
query: {'name': 'Kate Wills'},
update: { $set: {age: 50}},
new: true // default is false
});
--Return the last record BEFORE modification

db.users.findAndModify({ query: {'name': 'Kate Wills'}, update: { $set: {age:


40}}});
db.users.find({ name: 'Kate Wills'});

db.links.findAndModify({
query: {favorites: 100},
update: { $inc: { favorites: 10}},
fields: {title: 1, favorites: 1, _id: 0},
new: true // default is false
});

--Remove
--To Populate data
for (i=1; i<=20; i++) { db.testcol.insert( { _id : i, a : i } ) }

--Remove the first document


db.testcol.remove( { a : 1 } ) // Remove the first document

--Remove using Operator


db.testcol.remove( { a : { $lt : 5 } } ) // Remove three more
db.testcol.remove( { a : { $lt : 10 } },{ justOne : true } ) // Remove one
more

--Remove all the documents


db.testcol.remove() // Error: requires a query document.
db.testcol.remove( { } ) // All documents removed

--Dropping a Collection
db.colToBeDropped.insert( { a : 1 } )
show collections // Shows the colToBeDropped collection
db.colToBeDropped.drop()
show collections // collection is gone

--Dropping Database
use tempDB
db.testcol1.insert( { a : 1 } )
db.testcol2.insert( { a : 1 } )
show dbs // Here they are
show collections // Shows the two collections
db.dropDatabase()
show collections // No collections
show dbs // The db is gone
use sample // take us back to the sample db

-----------------------------------------------------------------------------------
----------------

--MongoDB Indexes
--Creating Single Field Index
--Checking the plan before Index is created
db.links.find({'title': 'Nettuts+'});
db.links.find( {title: 'Nettuts+'}).explain();

--Creating Index
db.links.ensureIndex({title: 1});
db.links.createIndex({title:1})
db.system.indexes.find();

--Checking the plan after Index is created


db.links.find({'title': 'Nettuts+'});
db.links.find( {title: 'Nettuts+'}).explain();

--Dropping Index
db.links.dropIndex({title:1})

--Creating Compound Index


--Creating Index
db.links.ensureIndex({title: 1, url: 1});
db.links.createIndex({title: 1, url: 1});
db.system.indexes.find();

--Checking the plan after Index is created


db.links.find({'title': 'Nettuts+'});
db.links.find( {title: 'Nettuts+'}).explain();
db.links.find( ).sort({title: 1, url: 1}).explain();
db.links.find( ).sort({title: -1, url: 1}).explain();
db.links.find( ).sort({title: 1, url: -1}).explain();
db.links.find( ).sort({title: -1, url: -1}).explain();

--Dropping Index
db.links.dropIndex({title:1})
db.links.dropIndex({title:1,url:1})

--Multikey Index
db.links.ensureIndex({tags: 1});
db.links.createIndex({tags: 1});
db.system.indexes.find();

db.links.find({tags:"marketplace"})
db.links.find({tags:"marketplace"}).explain()

--Text Index
db.reviews.createIndex( { comments: "text" } )

---GeoSpatial Index

db.places.insert(
{ name : "USA",
addresses : [ {
context : "home" ,
loc : [ 55.5, 42.3 ]
} ,
{
context : "home",
loc : [ -74 , 44.74 ]
}
]
})

db.places.createIndex( { "locs": "2d" } )

---Hash Indexes
db.links.dropIndex({tags:1})
db.system.indexes.find();
db.links.createIndex({"tags":"hashed"})
db.links.createIndex({"favorites":"hashed"})

---Test data for Sparse Index Testing


db.sparse_test.insert({a:1,b:2})
db.sparse_test.insert({a:1,b:3})
db.sparse_test.insert({a:1,b:4})
db.sparse_test.insert({a:1,b:5})
db.sparse_test.insert({a:1})
db.sparse_test.insert({a:2})
db.sparse_test.insert({a:3})
db.sparse_test.insert({a:4})
db.sparse_test.insert({a:5})

--Index Properties: Sparse Index

db.system.indexes.find({"ns":"balaji.sparse_test"}).pretty()
db.sparse_test.createIndex({b:1},{sparse:true})
db.system.indexes.find({"ns":"balaji.sparse_test"}).pretty()
db.sparse_test.ensureIndex({b:1},{sparse:true})

db.sparse_test.find({b:{$exists : true}}).explain()
db.sparse_test.find({b:{$exists : false}}).explain()
db.sparse_test.find({b:{$exists : false}}).hint({b:1}).explain()
db.sparse_test.find({a:1}).explain()
db.sparse_test.find({b:2}).explain()
db.sparse_test.find({b:""}).explain()

--Unique Index
db.system.indexes.find({"ns":"balaji.unq_test"}).pretty()
db.unq_test.createIndex({b:1},{unique:true})
db.system.indexes.find({"ns":"balaji.unq_test"}).pretty()
db.unq_test.insert({a:1,b:2})
db.unq_test.insert({a:1,b:3})
db.unq_test.insert({a:1,b:4})
db.unq_test.insert({a:1,b:5})
db.unq_test.insert({a:1})
db.unq_test.insert({a:2})

db.unq_test.find({b:2}).explain()
db.unq_test.find({b:""}).explain()

--Index Properties : TTL Index

db.system.indexes.find({"ns":"training.ttl_test"}).pretty()
db.collection.ensureIndex( { field_name : 1 },{ expireAfterSeconds : 30 } )
db.system.indexes.find({"ns":"training.ttl_test"}).pretty()

--Open 1 mongo shell window and execute the following


db.ttl_test.drop()
db.ttl_test.ensureIndex( { a : 1 }, { expireAfterSeconds : 30 } )
i = 0
while (true) {
i += 1;
db.ttl_test.insert( { a : ISODate(), b : i } );
sleep(1000); // Sleep for 1 second
}
--Check the records from the other window
db.ttl_test.find()

--Index Properties : Covered Index

db.covered.insert({ text: "hello", site: "home"});


db.covered.insert({ text: "hello", site: "work" });

db.covered.ensureIndex({text: 1, site: 1});

db.covered.find({text: "hello"}, {_id: 0, text:1, site:1}).explain();


db.covered.find({text: "hello"}, {text:1, site:1}).explain();

--Many to Many
--Authors:
db.authors.insert({ _id: 1, name: "Peter Standford", books: [1, 2] } );
db.authors.insert({ _id: 2, name: "Georg Peterson", books: [2] });

--Books:
db.books.insert({ _id: 1, title: "A tale of two people", categories:
["drama"], authors: [1] });
db.books.insert({ _id: 2, title: "A tale of two space ships", categories:
["scifi"], authors: [1,2] });

var booksCollection = db.books;


var authorsCollection = db.authors;
var author = authorsCollection.findOne({name: "Peter Standford"});
var books = booksCollection.find({_id: {$in: author.books}}).toArray();
var booksCollection = db.books;
var authorsCollection = db.authors;
var book = booksCollection.findOne({title: "A tale of two space ships"});
var authors = authorsCollection.find({_id: {$in: book.authors}}).toArray();

-----------------Replication---------------------------
--Setting up Replication

1) Create 3 folders
c:\data\rs0,c:\data\rs1,c:\data\rs2

2) Start all mongod

mongod --port 27017 --dbpath c:\data\rs0 --replSet rs0 --logpath


c:\data\rs0\log.rs0 --logappend --oplogSize 50 �journal
mongod --port 27018 --dbpath c:\data\rs1 --replSet rs0 --logpath
c:\data\rs1\log.rs1 --logappend --oplogSize 50 �journal
mongod --port 27019 --dbpath c:\data\rs2 --replSet rs0 --logpath
c:\data\rs2\log.rs2 --logappend --oplogSize 50 --journal

start "REPL-0" mongod --port 27017 --dbpath c:\data\rs0 --replSet rs0


--logpath c:\data\rs0\log.rs0 --logappend --oplogSize 50 --journal
start "REPL-1" mongod --port 27018 --dbpath c:\data\rs1 --replSet rs0
--logpath c:\data\rs1\log.rs1 --logappend --oplogSize 50 --journal
start "REPL-2" mongod --port 27019 --dbpath c:\data\rs2 --replSet rs0
--logpath c:\data\rs2\log.rs2 --logappend --oplogSize 50 �journal

3) Login to Default port mongod(27017) using mongo shell


mongo
or
mongo �port 27017

4) Set the Configuration


config = {_id: "rs0", members:[
{_id: 0, host: '10.50.47.86:27017'},
{_id: 1, host: '10.50.47.86:27018'},
{_id: 2, host: '10.50.47.86:27019'}]
}
Note: Change the IP address. use the variable to "config" initiate

5) Check the status initially


rs.status()
{
"startupStatus" : 3,
"info" : "run rs.initiate(...) if not yet done for the set",
"ok" : 0,
"errmsg" : "can't get local.system.replset config from self or any seed
(EMPTYCONFIG)"
}
6) Initiate the Replica set
rs.initiate(config)

7) Check the Replica set status


rs.status()
rs.printReplicationInfo()
db.printReplicationInfo()
db.getReplicationInfo()

db = db.getSiblingDB("local")
db.oplog.rs.find().sort({$natural:-1}).limit(1)
db.oplog.rs.find({ts:{$type:17}}).sort({$natural:-1}).limit(1)

-----Testing the Replication

Note : Open 2 mongo shell Windows/Terminals

Step 1) Issue Following command in Window 1

use test;

prompt = function() { return new Date() + "> " }

db1 = (new Mongo("10.50.47.86:27017")).getDB("test")


db2 = (new Mongo("10.50.47.86:27018")).getDB("test")
db3 = (new Mongo("10.50.47.86:27019")).getDB("test")

db1.setSlaveOk();
db2.setSlaveOk();
db3.setSlaveOk();

Step 2) Issue Following command in Window 2

prompt = function() { return new Date() + "> " }

db.test.insert({a:1,b:"test 1"})
var copy = db.test.findOne();

for (var i = 1; i< 10001; i++){


copy._id = new ObjectId();

j = "test " + i
copy.a= i;
copy.b=j;

db.customer.insert(copy);
}

---To insert the data in background


nohup mongo clm --eval 'var copy = db.customer.findOne();for (var i = 1; i<
2500000; i++){copy._id = new ObjectId();db.customer.insert(copy);}' &

Step 3) Issue the following Commands in Window1(Parallel)

db.printReplicationInfo();
db.printSlaveReplicationInfo();

db1.customer.count();
db2.customer.count();
db3.customer.count();

Note: There may not be any lag if not much load on primary. Data will be
immediately replicated

---Changing the Configuration: Priority


1) Fetch the current configuration into a Variable

cfg = rs.conf()

2) Change each member�s priority value

cfg.members[0].priority = 1
cfg.members[1].priority = 1
cfg.members[2].priority = 1

3) Assign the replica set the new configuration.

rs.reconfig(cfg)

4) Check the status Immediately - Rpimary would have become secondary

rs.status()

---Changing the Configuration: Hidden

1) Fetch the current configuration into a Variable

cfg = rs.conf()

2) Change each member�s priority value


cfg.members[1].hidden=true

3) Assign the replica set the new configuration.

rs.reconfig(cfg)

4) Check the status Immediately

rs.status()

---Changing the Configuration: Hidden

1) Fetch the current configuration into a Variable

cfg = rs.conf()

2) Change each member�s priority value

cfg.members[1].hidden=true

3) Assign the replica set the new configuration.

rs.reconfig(cfg)

4) Check the status Immediately

rs.status()

---Changing the Configuration: Votes

Note: Create 4 node replica set and give Votes=2 to one node and shutdown
other 2 nodes.
You can still find the DB is writable as one node has 2 votes and
majority become 3.

1) Fetch the current configuration into a Variable

cfg = rs.conf()

2) Change each member�s priority value

cfg.members[1].votes=2

3) Assign the replica set the new configuration.

rs.reconfig(cfg)
4) Check the status Immediately

rs.status()

--Adding & Removing Node

1) Create the folder


C:\data\rs3
2) Start the mongod
start "REPL-3" mongod --port 27020 --dbpath c:\data\rs3 --replSet rs0
--logpath c:\data\rs2\log.rs3 --logappend --oplogSize 50 --journal
3) Add the Node
mongo �port 27019
rs.add(�10.50.47.86:27020�)

4) Check the folder


rs.reconfig(cfg)

5) Check the status Immediately


rs.status()

6) Remove the node


rs.remove("10.50.47.86:27020")

Note: 1) Files will not be deleted. Manually we need to delete after node
removal.

------Sharding

Note:- Run all the commands in shell/command prompt


Step1) Setup Configure server ( Start 3 Config servers)
start "CFG0" mongod --configsvr --dbpath D:\MongoDb\Data\cfg0 --port 26050
--logpath D:\MongoDb\Logs\log.cfgo �logappend

start "CFG1" mongod --configsvr --dbpath D:\MongoDb\Data\cfg1 --port 26051


--logpath D:\MongoDb\Logs\log.cfg1 �logappend

start "CFG2" mongod --configsvr --dbpath D:\MongoDb\Data\cfg2 --port 26052


--logpath D:\MongoDb\Logs\log.cfg2 �logappend
Step2) Setup & start Shard Servers
start "SHARD0-rs0" mongod --shardsvr --dbpath D:\MongoDb\Data\sh0-rs0 --port
27000 --logpath D:\MongoDb\Logs\log.sho --logappend --smallfiles --oplogSize 50
--journal

start "SHARD1-rs0" mongod --shardsvr --dbpath D:\MongoDb\Data\sh1-rs0 --port


27100 --logpath D:\MongoDb\Logs\log.sh1 --logappend --smallfiles --oplogSize 50
--journal

start "SHARD2-rs0" mongod --shardsvr --dbpath D:\MongoDb\Data\sh2-rs0 --port


27200 --logpath D:\MongoDb\Logs\log.sh2 --logappend --smallfiles --oplogSize 50
--journal

start "SHARD3-rs0" mongod --shardsvr --dbpath D:\MongoDb\Data\sh3-rs0 --port


27300 --logpath D:\MongoDb\Logs\log.sh3 --logappend --smallfiles --oplogSize 50
--journal
Step3) Configuring Mongos servers
start "mongoS-0" mongos --configdb
BAIYERLAK1:26050,BAIYERLAK1:26051,BAIYERLAK1:26052 --logpath
D:\MongoDb\Logs\log.mongos0 --logappend --port 26060

start "mongoS-1" mongos --configdb


BAIYERLAK1:26050,BAIYERLAK1:26051,BAIYERLAK1:26052 --logpath
D:\MongoDb\Logs\log.mongos1 --logappend --port 26061

start "mongoS-2" mongos --configdb


BAIYERLAK1:26050,BAIYERLAK1:26051,BAIYERLAK1:26052 --logpath
D:\MongoDb\Logs\log.mongos2 --logappend --port 26062
Step4) Connect to 1 mongos and created cluster
mongo --port 26060

# Connect to config database


Use config

# Add shards to the configuration db


sh.addShard("BAIYERLAK1:27000");
sh.addShard("BAIYERLAK1:27100");
sh.addShard("BAIYERLAK1:27200");
sh.addShard("BAIYERLAK1:27300");

# Connect to test database


Use test
#Enable sharding for test database
sh.enableSharding("test");

#Shard a collection on fields a and b


sh.shardCollection("test.testcol", { a : 1, b : 1 } )

#Populate data to check the sharding


for (i=0; i<10000; i++) { docArr = []; for (j=0; j<1000; j++)
{ docArr.push( { a : i, b : j, c : "Filler String
00000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000" } ) };
db.testcol.insert(docArr) }

# Check the Sharding Status and details.


sh.status()
db.testcol.stats()

You might also like