Essentials of MongoDB & Mongo Shell underlying JavaScript

MongoDB is a free and open-source cross-platform document-oriented database program. wiki

User1 {
firstName :"John",
lastName: "Doe",
email:"jdoe@example.com",
userId:"jdoe"
}
User2 {
firstName :"Charlie",
lastName :"Sheen",
email:"charlies@example.com",
userId:"csheen",
mobile:"+1-234-xxx-xxx",
address:"Malibu House",
hobbies: {
"Playing piano",
"Driving"
}
}
  • Scale horizontally (distributed system)
  • Scale vertically (enable a single system to add resources to perform well)
  • BASE VS ACID:
  • Atomic
  • Consistent
  • Isolated
  • Durable
  • Basic Availability
  • Soft-state
  • Eventual consistency

<database/namespace>.<collection>.<operation>

Mongo Shell (MongoDB shell version v 3.4.10)

mongo -h
if (typeof Mongo == "undefined") 
{ Mongo = function(host) {
this.init(host);
};
}

Checking Databases (namespace for collections);

> show dbs;> use <database-name>;
// if db didn't exists, it will create a new.
> use sample
switched to db sample
// Create a collection
> db.createCollection("userDoc")
{ "ok" : 1 }
// List Collection in the database;> show collectionstest-test
test
example
userDoc

Collections:

> db.userDoc.count()
0
//return count of documents in the collection
> db.test-test.count()
// It will give error due to "-" special character.
> db["test-test"].count()
////return number of documents in the collection
> typeof(db)
//object
> var database = db>database.test.count()
//return count of documents in the collection
>var user1 =
{
"_id" : 1,
"userID" : "jDoe",
"address" : {
"building" : "230",
"coord" : [
-73.996089,
40.675018
],
"street" : "Huntington St",
"zipcode" : "11231"
},
"email" : "test@example.com",
"languages" : [
{
"speaks" : "English"
},
{
"speaks" : "German"
},
{
"speaks" : ""
}
],
"Bio" : [
{
"summary" : "I am work as software developer",
"date" : ISODate("2013-09-11T00:00:00Z")
},
{
"summary" : "total experience of 3 years",
"date" : ISODate("2013-01-24T00:00:00Z")
}
],
"name" : "John Doe",
"user_id" : "30075445"
}

> db.userDoc.insert(user1);
WriteResult({ "nInserted" : 1 })
> var q = db.userDoc.find()
> q
{ "_id" : 1, "userID" : "jDoe", "address" : { "building" : "230", "coord" : [ -73.996089, 40.675018 ], "street" : "Huntington St", "zipcode" : "11231" }, "email" : "test@example.com", "languages" : [ { "speaks" : "English" }, { "speaks" : "German" }, { "speaks" : "" } ], "Bio" : [ { "summary" : "I am work as software developer", "date" : ISODate("2013-09-11T00:00:00Z") }, { "summary" : "total experience of 3 years", "date" : ISODate("2013-01-24T00:00:00Z") } ], "name" : "John Doe", "user_id" : "30075445" }
> print(q)
DBQuery: test.userDoc -> { }
>printjson(q)
{
{<Object>
Supported functions
}
>q.help()

find(<predicate>, <projection>) modifiers
.sort({...})
.limit(<n>)
.skip(<n>)
.batchSize(<n>) - sets the number of docs to return per getMore
.collation({...})
.hint({...})
.readConcern(<level>)
.readPref(<mode>, <tagset>)
.count(<applySkipLimit>) - total # of objects matching query. by default ignores skip,limit
.size() - total # of objects cursor would return, honors skip,limit
.explain(<verbosity>) - accepted verbosities are {'queryPlanner', 'executionStats', 'allPlansExecution'}
.min({...})
.max({...})
.maxScan(<n>)
.maxTimeMS(<n>)
.comment(<comment>)
.snapshot()
.tailable(<isAwaitData>)
.noCursorTimeout()
.allowPartialResults()
.returnKey()
.showRecordId() - adds a $recordId field to each returned object
Cursor methods
.toArray() - iterates through docs and returns an array of the results
.forEach(<func>)
.map(<func>)
.hasNext()
.next()
.close()
.objsLeftInBatch() - returns count of docs left in current batch (when exhausted, a new getMore will be issued)
.itcount() - iterates through documents and counts them
.getQueryPlan() - get query plans associated with shape. To get more info on query plans, call getQueryPlan().help().
.pretty() - pretty print each document, possibly over multiple lines
> q.hasNext()
false
var q = db.userDoc.find()
> q.map(x => x)
[
{
"_id" : 1,
"userID" : "jDoe",
"address" : {
"building" : "230",
"coord" : [
-73.996089,
40.675018
],
"street" : "Huntington St",
"zipcode" : "11231"
},
"email" : "test@example.com",
"languages" : [
{
"speaks" : "English"
},
{
"speaks" : "German"
},
{
"speaks" : ""
}
],
"Bio" : [
{
"summary" : "I am work as software developer",
"date" : ISODate("2013-09-11T00:00:00Z")
},
{
"summary" : "total experience of 3 years",
"date" : ISODate("2013-01-24T00:00:00Z")
}
],
"name" : "John Doe",
"user_id" : "30075445"
}
]
> var q =db.userDoc.find()
> q.map(x => x._id)
[ 1 ]
> var q =db.userDoc.find()
> q.map(x => x.userID)
[ "jDoe" ]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store