Step Into mongo shell

Tips: retrieve previous commands issued in shell with up or down arrow key (Windows something like, C:\Users\myaccount.dbshell)

Start Shell

1
2
3
4
5
6
7
//start shell without connection to a database
mongo --nodb

//execute js file
mongo localhost:27017/testDB file.js
//alternative use load function n the shell
load("file.js") // execute js, file.js located on "data" directory

Basic commands

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
use <db_name>				// switch current db to db_name
show dbs / databases // list all databases on server
show collections / tables // list all tables on current db
db or db.getName) // show current db in shell
//
show roles // list all roles of current db
show users // list all users of current db
show profile
//how to get command reference in the shell
help or db.help() or db.collection.help()

//database can created automatically when saving data to MongoDB in shell
//Delete a database
db.dropDatabase() //drop current dtabase, delete all associated files
//Delete a collection
db.collection.drop() //remove table and index
//running in secure mode
db.auth() //authenticate user
// refer to another database using same connection
db.getSiblingDB(); //without explicitly switch the current database

CRUD at mongo shell

Overview

1
2
3
4
5
6
7
8
9
10
table = db.myCollection;	//table refer a specific collection
table.find(); //return a cursor
table.findOne(); //return a single document or null
table.count(); //count of documents
table.save(); //insert new or update existing document
table.insert(); //insert new document
table.update(); //update existing document
table.remove(); //delete existing document
//build index
table.createIndex();

Create&Update

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Loop samples in shell
use my //switch current db to my
for( var i=1;i<=200;i++) db.my.save({tag:"number",val:i});
for( var i=201;i<=250;i++) db.my.save({tag:i});
//it command
it //iterate cursor
//Loop to return all
var cursor = db.my.find();
//method I
while( cursor.hasNext()) {
printjson(cursor.next());
}
//method II
cursor.forEach(printjson);
//method III
var myArray = db.my.find().toArray();
printjson(myArray[2]);
//update
db.my.update({val:6},{$set:{tag:"NUMBER"}});
// to very update
db.my.find().limit(20);

Query

1
2
3
4
5
6
7
//SQL: select tag, val from my where tag = "number"
db.my.find({tag:"number"}).count();
db.my.find({tag:"number"},{val:true,tag:true}).limit(16);
db.my.findOne({tag:"number"},{val:true});
db.my.find({tag:"number"},{val:true,tag:true}).forEach(printjson);
//SQL: select * from my where tag > 200
db.my.find({tag:{$gt:200}}).forEach(printjson);

Delete

1
2
3
4
//remove() function
db.my.remove({tag:"NUMBER"});
// to verify
db.my.find().limit(20);