Essentials of MongoDB & Mongo Shell underlying JavaScript

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"
}
}

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" ]

#redhatter #opensource #developer #kubernetes #keycloak #golang #openshift #quarkus #spring https://mentorcruise.com/mentor/abhishekkoserwal/

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

dotenv for managing environment variables in NodeJS application

Some Important Things for JavaScript

All the things a Web developer needs to know for fluttering

React Native iOS Splash Screen Using Xcode Launch Screen

Putting Your App on a Solid Foundation with React Navigation

Leetcode Q125. Valid Palindrome

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
Abhishek koserwal

Abhishek koserwal

#redhatter #opensource #developer #kubernetes #keycloak #golang #openshift #quarkus #spring https://mentorcruise.com/mentor/abhishekkoserwal/

More from Medium

JavaScript, NoSQL and MongoDB

Which JS Framework Your Project Requires: Angular vs. React 2022

Javascript Error Handling

Authentication and Authorization with JWTs in Node && Express.js

Register Insomnia