Professional Documents
Culture Documents
Training Excercises
Training Excercises
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()
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()
db.hellos.insert( { _id : [ 1, 2, 3 ] } )
db.hellos.insert( { _id : 3 } )
db.hellos.insert( { _id : 3 } )
db.hellos.insert( { "Hello" } )
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)
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();
for(i=1;i<=10000;i++){
db.stuff.insert({
"a": i
})
}
db.stuff.find()
----CURSOR
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
---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()
--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 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});
---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();
--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'});
--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.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 } ) }
--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();
--Dropping Index
db.links.dropIndex({title:1})
--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 ]
}
]
})
---Hash Indexes
db.links.dropIndex({tags:1})
db.system.indexes.find();
db.links.createIndex({"tags":"hashed"})
db.links.createIndex({"favorites":"hashed"})
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()
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()
--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] });
-----------------Replication---------------------------
--Setting up Replication
1) Create 3 folders
c:\data\rs0,c:\data\rs1,c:\data\rs2
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)
use test;
db1.setSlaveOk();
db2.setSlaveOk();
db3.setSlaveOk();
db.test.insert({a:1,b:"test 1"})
var copy = db.test.findOne();
j = "test " + i
copy.a= i;
copy.b=j;
db.customer.insert(copy);
}
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
cfg = rs.conf()
cfg.members[0].priority = 1
cfg.members[1].priority = 1
cfg.members[2].priority = 1
rs.reconfig(cfg)
rs.status()
cfg = rs.conf()
rs.reconfig(cfg)
rs.status()
cfg = rs.conf()
cfg.members[1].hidden=true
rs.reconfig(cfg)
rs.status()
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.
cfg = rs.conf()
cfg.members[1].votes=2
rs.reconfig(cfg)
4) Check the status Immediately
rs.status()
Note: 1) Files will not be deleted. Manually we need to delete after node
removal.
------Sharding