install on mac
brew install mongodb
sudo chown `id -u` /data/db
sudo mongod
tools
mongo
MongoDB client as a javascript shell
mongoimport
importing JSON,CSV,or TSV data
mongoimport -d myapp -c users --file user_data.json
mongoexport
exporting data on JSON or csv
mongoexport -d myapp -c users --out user_data.json
mongodump
creating a binary export
mongorestore
restoring a binary export
mongorestore -d myapp ../dump/myapp
bsondump
converting a binary export to JSON
bsondump dump/myapp/users.bson > users.json
mongostat
overviewing the status of the MongoDB server
BSON
http://bsonspec.org/
NoSQL Database Terms
Database
Collections
Like on RDBMS Table
No schema
Document
Like on RDBMS Record,or Row
Field
Like on RDBMS Column
{ key:value }
Create DATABASE
show dbs
use text
use new_database_name //create new database
db //show current db name
db.collectionname
db.collectionname.count() //count collections
db.links.insert({'title':'Test link',url:'http://www.baidu.com',comment:'some test comment',tags:[ 'tag1','tag2','tag3' ],saved_on:new Date()})
var doc = {};
doc.title = 'title';
doc.url = 'some url';
doc.tags = ['tag1','tag2'];
doc.saved_on = new Date;
doc.meta = {};
doc.meta.browser = 'google chrome 24';
doc.meta.OS =‘Mac OS 10.7.4';
db.links.save(doc)
db.links.find()
db.links.find().forEach(printjson)
db.links.find().pretty()
db.links.insert({_id:3,name:'test'})
db.links.find[0]
db.links.find[0]._id
db.links.find[0]._id.getTimestamp()
new ObjectId
function counter(name) {
var ret = db.counters.findAndModify({query:{_id:name},update:{$inc:{next:1}},'new':true,upsert:true});
return ret.next;
}
db.products.insert({_id:counter('product'),name:'product 1'});
db.products.insert({_id:counter('product'),name:'product 2'});
Relations
db.users.insert({name:'jack'})
var a = db.users.findOne({name:'jack'})
db.links.insert({title:'test',url:'some url',userId:a._id})
var b = db.links.find()[db.links.count()-1] //get the latest record
db.users.findOne({_id:b.userId})
Queries
mongo 127.0.0.1/bookmarks bookmarks.js
mongo bookmarks
db.users.find()
db.users.find().forEach(printjson);
db.users.find({email:'jack@admin.com'})
db.users.find({password_hash:'another_password_hash'})
db.users.find({favourites:100})
db.users.find({tags:'tag1'}) //find records that tags array contain 'tag1'
db.users.findOne({email:'jack@admin.com'})
db.users.find('',{name:1,_id:0}) //only get the name field
db.users.find('',{name:1,name:0}) //get all fields except the name field | exclude the name field
db.users.find('name.first':'jack')
db.users.find('name.first':'jack',{'name.last':1})
var jack = db.users.findOne('name.first':'jack',{'name.last':1})
Operators:
greater than
db.links.find({favourites:{$gt:30}})
less than
db.links.find({favourites:{$lt:30}})
less than equal to
db.links.find({favourites:{$lte:30}})
greater than equal to
db.links.find({favourites:{$gte:30}})
greater than and less than
db.links.find({favourites:{$gte:300,$lt:50}})
in
db.links.find({'name.first':{$in:['jack','john']}})
not in
db.links.find({'name.first':{$nin:['jack','john']}})
all
db.users.find({tags:{$all:['tag1','tag2']}})
not equal
db.users.find({tags:{$ne:'tag1'}})
if the filter object is a array,records that does not contain the specified value will be returned
for example:
tags = ['tag1']
tag1 = []
tag2 = ['tag2']
db.find({tag:{$ne:'tag'}}) will find tags,tag1 and tag2
or
db.users.find({$or:[{'name.first':'jack'},{'name.last':'jack'}]})
not or
db.users.find({$nor:[{'name.first':'jack'},{'name.last':'yao'}]})
//find records that name.first != 'jack' or name.last != 'yao'
and
db.users.find({$and:[{'name.first':'jack'},{'name.last':'yao'}]})
exists
db.users.find({tags:{$exists:true}})
not exists
db.users.find({tags:{$exists:false}})
mod
db.links.find({favourites:{$mod:[5,0]}})
not
db.links.find({favourites:{$not:{$mod:[5,0]}}})
elemMatch
db.users.find({logins:{$elemMatch:{minutes:20}}})
db.users.find({logins:{$elemMatch:{minutes:20,at:{$lt:new Date(2014,6,22)}}}})
where
db.users.find({$where:'this.name.first === "jack"'})
db.users.find({$where:'this.name.first === "jack"',age:20})
this
db.users.find('this.name.first === "jack"')
f = function () {return this.name.first === 'jack'};
db.users.find(f);
db.users.find({$where:f});
distinct
db.links.distinct('favourites')
db.links.distinct('url')
group
db.links.group({
key:{userId:true},
initial:{favCount:0},
reduce:function(doc,o){o.favCount += doc.favourites;},
finalize:function(o){o.name = db.users.findOne({_id:userId}).name;}
})
regular expression
$regex
db.links.find({title:/title/})
db.links.find({title:{$regex:/title/}})
db.links.find({title:{$regex:/title/,$ne:'title'}})
db.links.find({title:{$regex:/title\+$/,$ne:'title'}})
count
db.users.find({'name.first':'jack'}).count()
db.users.count({'name.first':'jack'})
db.users.count()
sort
db.links.find({},{title:1,_id:0})
db.links.find({},{title:1,_id:0}).sort({title:1}) //ASC
db.links.find({},{title:1,_id:0}).sort({favourites:-1}) //DESC
db.links.find({},{title:1,favourites:1,_id:0}).sort({favourites:-1,title:1})
limit
db.links.find({},{title:1,_id:0,favourites:1}).sort({favourites:-1}).limit(1)
paging
db.links.find({},{title:1,_id:0,favourites:1}).sort({favourites:-1}).skip(0*3).limit(1)
updates
db.users.update({'name.first':'jack'},{job:'developer'})//replacement
upsert
db.user.update({name:'jason'},{name:'kate'},true)
modification operators
inc
db.users.update({age:30},{$inc:{age:1}})
update multiple documents
db.users.update({},{$inc:{age:1}},false,true)
set
db.users.update({},{$set:{age:1}},false,true)
set an unexist key
db.users.update({},{$set:{email:'yaowenqiang111@163.com'}},false,true)
unset
db.users.update({},{$unset:{email:'yaowenqiang111@163.com'}},false,true)
save
user = db->users->findOne();
user.name = 'new name';
db.users.save(user);
find and modify
db.users.findAndModify({
query:{name:'jack'},
update:{$set:{age:30}},
sort:{age:1},
fields:{title:1,age:1,_id:0},
new:false //return data update before
new:true //return data update after
})
push
db.links.update({},{$push:{tags:'blog'}})
//push a array into a array
db.links.update({},{$push:{tags:['blog','tag3']})
push all
db.links.update({},{$pushall:{tags:['blog','about']}})
addToSet //add no-repeat value into a array
db.links.update({},{$addToSet:{tags:['blog','about']}})
each
db.links.update({},{$addToSet:{tags:{$each:['one','four']}}})
pull
db.links.update({},{$pull:{tags:['blog','about']}})
pull all same values from an array
db.links.update({},{$pull:{tags:['blog','about']}},false,true)
pull all
db.links.update({},{$pullAll:{tags:['blog','about']}})
pop
//pop one element from an array
db.links.update({},{$pop:{tags:1}}) //1 mean pop the end
db.links.update({},{$pop:{tags:-1}}) //1 mean pop the head
position update
db.users.update({'logins.minutes':20},{$inc:{'logins.$.minutes':10}},false,true)
//$ means the position of the matched array's index
/*random*/
/*db.users.update({'logins.minutes':20},{$set:{random:true}},false,true)*/
rename
db.users.update({},{$rename:{logins:'log'}},false,true)
remove a document
db.users.remove()
remove with specified documents
db.users.remove({age:10})
use findandmodify to remove documents
db.users.findandmodify({
query:{{age:1}},
remove:true
})//the removed documents will be returned
show collections
show collections
delete a collection
db.collectionname.drop()
i.e,db.users.drop()
drop a database
db.dropDatabase()
query explain
db.users.find({age:3}).explain()
db.users.find({age:1}).explain()
{
"cursor" : "BasicCursor",//not using any indexed
"nscanned" : 4,
"nscannedObjects" : 4,
"n" : 3,//numbers of documents returned
"millis" : 4,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
}
}
db.users.find({_id:ObjectId("53a6fa35882c4f1b662dfeeb")}).explain()
{
"cursor" : "BtreeCursor _id_",
"nscanned" : 1,
"nscannedObjects" : 1,
"n" : 1,
"millis" : 2,
"nYields" : 0,
"nChunkSkips" : 0,
"isMultiKey" : false,
"indexOnly" : false,
"indexBounds" : {
"_id" : [
[
ObjectId("53a6fa35882c4f1b662dfeeb"),
ObjectId("53a6fa35882c4f1b662dfeeb")
]
]
}
}
create index
db.users.ensureIndex({title:1})
index parameters
unique
db.users.ensureIndex({title:1},{unique:true})
drop Dups
db.users.ensureIndex({title:1},{unique:true,dropDups:true})
show indexes
db.system.indexes.find()
sparse(罕/少见的) index
db.ensureIndex({title:1},{sparse:true})//documents that does not have the index key will not be indexed
component index
<<MongoDB In Action>>
db.links.ensureIndex({title:1,url:1})
Note:mongodb can use only one index per query
drop index
db.links.drpIndex('indexname')
vagrant
vagrant box add mongo-server mongo.box
mkdir mongo-php
cd mongo-php
vagrant init mongo-server
vim VagrantFile
uncomment the line below:
config.vm.forward_port 80,8888
vagrant up //start the virtual machine
vagrant ssh
vagrant halt && vagrant up
nodejs
install the latest node and npm
sudo npm install -g express-generator
create project
express mongodb-js
cd mongodb-js
change the package.json
{
name: mongo-js,
version: 0.0.1,
private: true,
scripts: {
"start": "nodemon app.js"
},
dependencies: {
express: ~4.2.0,
static-favicon: ~1.0.0,
morgan: ~1.0.0,
cookie-parser: ~1.0.1,
body-parser: ~1.0.0,
debug: ~0.7.4,
jade: ~1.3.0
mongodb:*,
nodemon:*
}
}
// TODO nodejs with mongo
npm install
rm routes public
vim app.js
rm route user path
add mongo
mongo = require('mongodb')