Install
on Linux
Run Mongodb with Bitnami
This is the recommended way to use mongodb for dev purpose, especially on laptop.
First download bitnami mongodb installer, for example,
bitnami-mongodb-3.4.0-0-linux-x64-installer.run,
from MongoDB Stack.
Run it to install in a local folder, say (MONGODB_HOME*.
Modify bind_ip
to 0.0.0.0
and auth
to false
in *\)MONGODB_HOME/mongodb/mongodb.conf
to make it can be accessed from remote, and turn off authentication.
Run ./ctlscript.sh restart
to reload the new conf.
Install as a service
Install, run and uninstall mongodb with aptitude.
Ref: Install MongoDB on Ubuntu
Start mongodb server as a common user
The default data path of Mongodb is /data/db, which you have to create as root.
If you just want play around mongodb with some test data, you can create a temporary folder as data directory:
$ mkdir ~/docs/tmp/mongodb-repo
$ cd ~/apps/mongodb-linux-x86_64-2.6.5
$ bin/mongod --dbpath ~/docs/tmp/mongodb-repo
// in a new shell
$ ~/apps/mongodb-linux-x86_64-2.6.5/bin/mongo
For convenience, add PATH=$HOME/apps/mongodb-linux-x86_64-2.6.5/bin:$PATH
into ~/.zshenvr,
and alias mongod='mongod --dbpath /home/chad/docs/tmp/mongodb-repo'
into ~/.bash_alias.
Make sure the following lines exist in ~/.zshrc:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
Now we can start mongo server and client anywhere in a shell.
Run mongod via sudo
-
Extract MongoDB package to /opt as root and
mkdir -p /data/db
; -
Add MongoDB path into common user's .zshenv:
PATH=$PATH:/opt/mongodb-linux-x86_64-ubuntu1404-3.0.3/bin
; -
Add
alias mongod='sudo env PATH=$PATH mongod'
into .bash_aliases;
Now as a common user, start mongodb service with mongod
, run client via mongo
.
Note: Do NOT add alias sudo='sudo env PATH=$PATH'
into .bash_aliases,
as suggested in http://stackoverflow.com/questions/257616/sudo-changes-path-why#
For this will modify sudo's PATH globally. And the auto-completion won't work.
For example: sudo apti<Tab>
can't be converted to sudo aptitude
.
on Windows
Install with choco install mongodb
.
Start server with mongod --dbpath "C:\Users\lee_c\AppData\Local\Temp"
in folder C:\Program Files\MongoDB\Server\3.4\bin.
Database Management
First start mongo server mongod
. Then start the client with mongo
.
All the following commands is running in mongo shell, whose prompt is '> '.
List all existing database: show dbs
;
Create a new database "meteor" and switch to it: use meteor
;
Remove database "mydb": use mydb
, then db.dropDatabase()
;
Backup and Restore
-
Backup a database to a directory:
mongodump -d <db_name> -o <bak_dir>
; -
Backup a collection:
mongodump -d <db_name> -c <collection_name>
; -
Restore a collection:
mongorestore -d <target_db_name> -c <target_collection_name> <target_collection_name>.bson
;
Sync Database Remotely
Here we backup database "test" in local mongodb, transfer it to a remote host (we name it "ld"), and restore this database into host's mongodb.
# on local host
cd
mongodump -d test -c fairs
scp -r dump ld:~/
rm -rf dump
# on remote host ld
cd ~/dump
mongorestore -d meteor test
In the last command, the "meteor" is the target database, the following "test" is a folder name contains dumped data from local host.
Data Refinement
-
Remove duplicated documents in a collection ("fairs") based on a key ("chnName"):
db.fairs.ensureIndex({chnName:1}, {unique : true, dropDups : true})
; -
map-reduce example: the "mapReduce" function has 3 arguments: the mapper, the reducer, and the definition of input (query) and output (out).
The "emit" function has 2 arguments, the first is the "key", the 2nd is the value.
In the following demo, the first mapReducer calculates the average of all ranks of fair with id "54cef40a191f3bb2ef12bdf7", the second mapReducer calculates every fair's average of user ranks.
The result of mapReduce is put into a new collection, instead of returning a object.
> db.userComments.find() { "_id" : "5fSQFR4kSLGLc9nLk", "fairId" : "54cef40a191f3bb2ef12bdf7", "userId" : "gpxst3JwJNPT33maf", "rank" : 4 } { "_id" : "oRmXmdPnsvSQNSNK3", "fairId" : "54cef40a191f3bb2ef12bdf7", "userId" : "yiio2r3fQ64nqAC4j", "rank" : 5 } { "_id" : "DePtvHcNvwMpLPdq8", "fairId" : "54cef40a191f3bb2ef12bdf8", "userId" : "yiio2r3fQ64nqAC4j", "rank" : 2 } { "_id" : "eX9jWZt74cHMg3jAe", "fairId" : "54cef40a191f3bb2ef12bdf8", "userId" : "gpxst3JwJNPT33maf", "rank" : 5 } { "_id" : "xntPL4Pnyasen2jcx", "fairId" : "54cef40a191f3bb2ef12bdf8", "userId" : "bc3iNrRpN7Wdi26zP", "rank" : 4 } > db.userComments.mapReduce(function(){ emit(this.fairId, this.rank); }, function(key, values) { return Array.avg(values); }, { query: { fairId: "54cef40a191f3bb2ef12bdf7" }, out: "rank_avg" } ); { "result" : "rank_avg", "timeMillis" : 60, "counts" : { "input" : 2, "emit" : 2, "reduce" : 1, "output" : 1 }, "ok" : 1 } > db.rank_avg.find() { "_id" : "54cef40a191f3bb2ef12bdf7", "value" : 4.5 } > db.userComments.mapReduce(function(){ emit(this.fairId, this.rank); }, function(key, values) { return Array.avg(values); }, { out: "rank_avg" } ); > db.rank_avg.find() { "_id" : "54cef40a191f3bb2ef12bdf7", "value" : 4.5 } { "_id" : "54cef40a191f3bb2ef12bdf8", "value" : 3.6666666666666665 }
-
Update a element of an array:
db.Fair.update( { "nameZHCN": /117/ }, {$set: {"recurrence.0.expomap": "ZoimfczNHGMefysvt" } } )
; Note the double quotes of "recurrence.0.expomap" is mandatory.