Sei sulla pagina 1di 8

Tech Guides

OPEN

Home How To AskOTG Tutorials Certi cations Contact Us

MongoDB Cheat Sheet - Essential


MongoDB Shell Commands
Posted on 05th December 2016

H ere are the most commonly used Mongo Shell commands with
example usage.

Basic Commands
Run this
To do this Example
command

Connect to local
host on default mongo mongo
port 27017

mongo --host
Connect to remote mongo --host
<hostname or ip
host on speci ed 10.121.65.23 --port
address> --port
port 23020
<port no>

Connect to a mongo mongo


database <host>/<database> 10.121.65.58/mydb

Show current
db db
database

Select or switch use <database


use mydb
database [1] name>
Execute a load(< lename>) load (myscript.js)
JavaScript le

Display help help help

Display help on DB
db.help() db.help()
methods

Display help on
db.mycol.help() db.mycol.help()
Collection

Show Commands
Show all databases show dbs show dbs

Show all collections


show collections show collections
in current database

Show all users on


show users show users
current database

Show all roles on


show roles show roles
current database

CRUD Operations
db.books.insert({"is
bn":
9780060859749,
Insert a new "title": "After Alice:
db.collection.insert(
document in a A Novel", "author":
<document> )
collection [2] "Gregory Maguire",
"category":
"Fiction",
"year":2016})

Insert multiple db.collection.insert db.books.insertMa


documents into a Many([ ny( [{"isbn":
collection <document1>, 9780198321668,
<document2>, ... ]) "title": "Romeo and
-or- Juliet", "author":
"William
db.collection.insert(
Shakespeare",
[ <document1>,
<document2>, ... ]) "category":
"Tragedy", "year":
2008}, {"isbn":
9781505297409,
"title": "Treasure
Island", "author":
"Robert Louis
Stevenson",
"category":
"Fiction",
"year":2014}])
-or-
db.books.insert([{
"isbn":"9781853260
001", "title": "Pride
and Prejudice",
"author": "Jane
Austen", "category":
"Fiction"}, {"isbn":
"9780743273565",
"title": "The Great
Gatsby", "author":
"F. Scott
Fitzgerald"} ])

Show all
documents in the db.collection. nd() db.books. nd()
collection

Filter documents db.books. nd({"title


db.collection. nd(<
by eld value ":"Treasure
query>)
condition Island"})

db.books. nd({"title
Show only some db.collection. nd(< ":"Treasure
elds of matching query>, Island"}, {title:true,
documents <projection>) category:true,
_id:false})

Show the rst db.collection. ndO db.books. ndOne({


document that ne(<query>, }, {_id:false})
matches the query <projection>)
condition

db.books.update({ti
Update speci c
tle : "Treasure
elds of a single db.collection.updat
Island"}, {$set :
document that e(<query>,
{category
match the query <update> )
:"Adventure
condition
Fiction"}})

Remove certain db.books.update({ti


db.collection.updat
elds of a single tle : "Treasure
e(<query>,
document the Island"}, {$unset :
<update>)
query condition {category:""}})

Remove certain db.books.update({c


db.collection.updat
elds of all ategory : "Fiction"},
e(<query>,
documents that {$unset :
<update>,
match the query {category:""}},
{multi:true} )
condition {multi:true})

Delete a single db.books.remove({t


db.collection.remo
document that itle :"Treasure
ve(<query>,
match the query Island"},
{justOne:true})
condition {justOne:true})

Delete all
db.books.remove({"
documents db.collection.remo
category"
matching a query ve(<query>)
:"Fiction"})
condition

Delete all
db.collection.remo db.books.remove({}
documents in a
ve({}) )
collection

Index
Create an index db.collection.create db.books.createInd
Index( ex({title:1})
{indexField:type} )
Type 1 means
ascending; -1
means descending

db.collection.create
db.books.createInd
Create a unique Index(
ex( {isbn:1},
index {indexField:type},
{unique:true} )
{unique:true} )

db.collection.create
Create a index on Index({indexField1: db.books.createInd
multiple elds type1, ex({title:1,
(compound index) indexField2:type2, author:-1})
...})

Show all indexes in db.collection.getInd db.books.getIndexe


a collection exes() s()

db.collection.dropI
db.books.dropInde
Drop an index ndex(
x({author:-1})
{indexField:type} )

Show index
db.collection.stats() db.books.stats()
statistics

Cursor Methods
Show number of
db.books. nd().cou
documents in the cursor.count()
nt()
collection

Limit the number


db.books. nd().limi
of documents to cursor.limit(<n>)
t(2)
return

Return the result


set after skipping db.books. nd().skip
cursor.skip(<n>)
the rst n number (2)
of documents

Sort the cursor.sort( <{ eld : db.books. nd().sort


documents in a value}> ) ( {title : 1} )
result set in value = 1 for
ascending or
descending order ascending, -1 for
of eld values descending

Display formatted
db.books. nd({}).pr
(more readable) cursor.pretty()
etty()
result

Comparison Operators
{< eld>: { $eq: db.books. nd({year
equals to
<value> }} : {$eq: 2016}})

{< eld>: { $lt: db.books. nd({year


less than
<value> }} : {$lt: 2010}})

less than or equal {< eld>: { $lte: db.books. nd({ye


to <value> }} ar: {$lte: 2008}})

{< eld>: { $gt: db.books. nd({year


greater than
<value> }} : {$gt: 2014}})

greater than or {< eld>: { $gte: db.books. nd({year


equal to <value> }} : {$gte: 2008}})

{< eld>: { $ne: db.books. nd({year


not equal to
<value> }} : {$ne: 2008}})

{< eld>: { $in: [ db.books. nd({year


value in <value1>, <value2>, : {$in: [2008,
... }} 2016]}})

{< eld>: { $nin: [ db.books. nd({year


value not in <value1>, <value2>, : {$nin: [2008,
... }} 2016]}})

Logical Operators
db.books. nd( {
{ $or:
$or: [{year: {$lte:
OR [<expression1>,
2008}}, {year: {$eq:
<expression2>,...]}
2016}}]} )

AND { $and: db.books. nd( {


[<expression1>, $and: [{year: {$eq:
<expression2>,...]} 2008}}, {category:
{$eq: "Fiction"}}]} )

db.books. nd(
{ $not:
NOT {$not: {year: {$eq:
{<expression>}}
2016} }})

db.books. nd( {
{ $nor:
$nor: [{year: {$lte:
NOR [<expression1>,
2008}}, {year: {$eq:
<expression2>,...]}
2016}}]} )

Element Operators
Match documents db.books. nd(
{< eld>:
that contains that {category:
{$exists:true}}
speci ed eld {$exists: true }})

Match documents
db.books. nd(
whose eld value is {< eld>:
{category: {$type:
of the speci ed {$type:value}}
2 }})
BSON data type

[1] Databases are created on the y and will actually be created when
you insert something into it.

[2] Collections are created on the y when you insert rst document
into it.

Rate it

Related Articles

Post a comment

Comments
Your Comment....

Name Email

Post Comment

@89rtE | October 2, 2017 3:30 PM |


Lots of HW, GZ. THX.
Reply

Shy Tamir | December 29, 2016 10:46 AM |


You might want to add this little gem for validation of data les. I use it
on our restored daily backup to verify it's usable:
db.getSiblingDB("admin").runCommand("listDatabases").databases.forE
ach(function(d)
{db.getSiblingDB(d.name).getCollectionNames().forEach(function(c)
{assert(db.getSiblingDB(d.name).getCollection(c).validate().valid==true)}
)})
Reply

Copyright 2019 Open Tech Guides. All rights reserved

Potrebbero piacerti anche