Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 7

MongoDB Definition

MongoDB is an object-oriented, simple, dynamic, and scalable NoSQL database. It is based on the
NoSQL document store model where the data objects are stored as separate flexible, JSON-like
documents, inside a collection instead of storing the data into the columns and rows of a traditional
relational database. meaning fields can vary from document to document and data structure can be
changed over time.
The motivation of the MongoDB is to implement a data store that provides high performance, high
availability, and automatic scaling (horizontal scaling). MongoDB is extremely simple to install and
free to use. Versions released prior to October 16, 2018, are published under the AGPL and its
general distributions support Windows, Linux, Mac OS X, and Solaris.

Why is using MongoDB better than using


MySQL? 🤔
Organizations of all sizes are adopting MongoDB because it enables them to build applications
faster, handle highly diverse data types, and manage applications more efficiently at scale.
Development is simplified as MongoDB documents map naturally to modern, object-oriented
programming languages. Using MongoDB removes the complex object-relational mapping (ORM)
layer that translates objects in code to relational tables. MongoDB’s flexible data model also means
that your database schema can evolve with business requirements. MySQL's rigid relational
structure adds overhead to applications and slows developers down as they must adapt objects in
code to a relational structure.

Some keywords before we start


During this course we are going to use some technical words, so before we start let’s define them:
• Schema: a database schema is its structure described in a formal language supported by the
database management system. We can think of as a blueprint for our database.
• Document: The document is the unit of storing data in a MongoDB database.
document use JSON (JavaScript Object Notation, is a lightweight, thoroughly explorable
format used to interchange data between various applications) style for storing data. We can
think of it as a row in an Excel sheet.
• Collection: A collection may store a number of documents. We can compare it to the Excel
sheet it self.

Key benefits
• Schema less − MongoDB is a document database in which one collection holds different
documents. Number of fields, content and size of the document can differ from one
document to another. Optionally, schema validation can be used to enforce data governance
controls over each collection.
• Deep query-ability. MongoDB supports dynamic queries on documents using a document-
based query language MongoDB Query Language (MQL) that's nearly as powerful as SQL.
• Higher Availability − MongoDB automatically replicates your data to additional nodes for
high availability and durability. In the event of a system failure, failover completes
automatically - typically in less than 5 seconds.
• Faster Development MongoDB’s document data model maps naturally to objects in
application code, making it simple for developers to learn and use.
• Scale Infinitely and Cheaply (Ease of scale-out) − MongoDB includes native support for
distributing, or sharding, a database across any number of commodity machines in a way
that is transparent to the application.
MongoDB is generally used at theBackend
Which one of the following is correct?MongoDB is a NoSQL database.
MongoDB is X-based database?Document
What is supported by MongoDB?BSON
To install mongodb we need a special operating systemFalse
To verify the version of mongo we use the command: mongo –version
Mongo shell is the cli used to manipulate mongodb using the terminal True

️Database Management ️
db.getName()
Returns:the current database name.
db.version()
Returns:The version of the mongod or mongos instance.

db.stats(scale)
The db.stats() method returns a document with statistics reflecting the database system’s state
The scale factor for the various size data. The scale defaults to 1 to return size data in bytes. To
display kilobytes rather than bytes, specify a scale value of 1024.

️Database Management ️
Here is some other database methods:
• db.getName(): Returns the current database name.
• db.version(): Returns The version of the mongod or mongos instance.
• db.stats(scale): The db.stats() method returns a document with statistics reflecting the
database system’s state
• The scale factor for the various size data. The scale defaults to 1 to return size data in
bytes. To display kilobytes rather than bytes, specify a scale value of 1024.
• db.serverStatus(): Returns a document that provides an overview of the database process’s
state.
db.serverStatus( { repl: 0, metrics: 0, locks: 0 } )

• db.hostInfo(): Returns a document with information about the underlying system that the
mongod or mongos runs on.
• db.cloneDatabase("hostname"): Copies a remote database to the current database. The
command assumes that the remote database has the same name as the current database.
hostname string The hostname of the database to copy.
• db.copyDatabase(): Copies a database either from one mongod instance to the current
mongod instance or within the current mongod.
Which of the following can provide an insight of MongoDB database process’s state?serverStatus
What command will you use to show the current database name.?db.getName()db
To switch from one database to another we use the command Use <db_Name>

️Collection Management ️
Now after we learned how to manipulate a database, it’s time to manipulate the
collections of our database:
P.S. The methods listed on this table of contents page refer to the mongo shell methods, and not to
the MongoDB Node.js driver (or any other driver) methods.
• db.createCollection(): Because MongoDB creates a collection implicitly when the
collection is first referenced in a command, this method is used primarily for creating new
collections that use specific options. For example, you use db.createCollection() to create a
capped collection, or to create a new collection that uses document validation.
• db.collection.count(): Returns the count of documents that would match a find() query for
the collection or view. The db.collection.count() method does not perform the find()
operation but instead counts and returns the number of results that match a query.

️Collection Management ️
• db.collection.stats(): Reports on the state of a collection.
• db.collection.storageSize(): Reports the total size used by the collection in bytes.
• db.collection.validate(<option>): Validates a collection. The method scans a collection data
and indexes for correctness and returns the result.
• full: Optional. A flag that determines whether the command performs a slower but
more thorough check or a faster but less thorough check.
db.collection.validate( {
full: <boolean> // Optional
} )

db.collection.validate( <boolean> ) // full option


️Collection Management ️
db.collection.explain(verbosity)
Returns information on the query plan for the following methods:

• aggregate()

• count()

• find()

• remove()

• update()

• distinct()

• findAndModify()
Verbosity: Optional. Specifies the verbosity mode for the explain output. The mode affects the
behavior of explain() and determines the amount of information to return. The possible modes are:

• "queryPlanner" (Default)

• "executionStats"

• "allPlansExecution"
db.products.explain("allPlansExecution").update( { $set: { reorder: true } })

Which one is not a verbosity mode in the method explain "anyPlansExecution"


What command will you use to show the total size used by the collection?
db.collection.storageSize()
Which of the following can provide collection’s documents count ? db.collection.count

CRUD operations
When we are dealing with databases,there are four operation that we can apply to a database:
• CREATE: or insert operations add new documents to a collection. If the collection does not
currently exist, insert operations will create the collection.
• READ: operations retrieves documents from a collection; i.e. queries a collection for
documents.
• UPDATE: operations modify existing documents in a collection.
• DELETE: operations remove documents from a collection
The four first letters of each word compose the CRUD word.
In computer programming,
create
, read,
update
, and delete (CRUD) are the four basic functions of storage. Alternate words are sometimes used
when defining the four basic functions of CRUD, such as
query
instead of read,
modify
instead of update, or
destroy
instead of delete

Create Document 📄
MongoDB provides the following methods to insert documents into a collection:

• db.collection.insert()

• db.collection.insertOne()

• db.collection.insertMany()

• db.collection.save()

Insert Document 📄
db.collection.insertOne()
Inserts a document into a collection.
db.collection.insertOne(
<document>,
{
writeConcern: <document>
}
)

• document: document to save to the collection.


• writeConcern: Write concern describes the level of acknowledgment requested from
MongoDB for write operations

Insert Document 📄
db.collection.save()
Updates an existing document or inserts a new document, depending on its document parameter.
The save() method uses either the insert or the update command, which use the default write
concern. To specify a different write concern, include the write concern in the options parameter.
db.collection.save(
<document>,
{
writeConcern: <document>
}
)
db.products.save( { item: "book", qty: 40 } )

• document: document to save to the collection.


• writeConcern: Write concern describes the level of acknowledgment requested from
MongoDB for write operations
Note: MongoDB deprecates the db.collection.save() method. Instead use db.collection.insertOne()
or db.collection.replaceOne() instead.
db.collection.save() is still a valid method for mongodbFalse
MongoDB provides the following methods to insert documents into a collection:
db.collection.insert() db.collection.insertOne() db.collection.insertMany()True
Which of the following operation adds a new document to the users collection?insert Which of the
following operation adds a new document to the users collection?insert
Which of the following method is used to query documents in collections?find
Point out the correct statement.Queries specify criteria, or conditions, that identify the documents
that MongoDB returns to the clients
What will be the output products with price greater than 18 and reviews greater than 400
Which of the following method returns one document?findOne()

Update Document 📄
db.collection.save()
Updates an existing document or inserts a new document, depending on its document parameter.
The save() method uses either the insert or the update command, which use the default write
concern. To specify a different write concern, include the write concern in the options parameter.
db.collection.save(
<document>,
{
writeConcern: <document>
}
)
db.products.save( { item: "book", qty: 40 } )

• document: document to save to the collection.


• writeConcern: Write concern describes the level of acknowledgment requested from
MongoDB for write operations
Note: MongoDB deprecates the db.collection.save() method. Instead use db.collection.insertOne()
or db.collection.replaceOne() instead.
What does the following query do when performed on the posts collection?
db.posts.update({ _id: 1 }, { $set: { Author: "Tom" } })

Adds a new field Author in the searched collection if not already presentUpdates only the Author
field of the document with _id as 1
Rewrite the following query using another mongoDB method
db.posts.update({ _id: 1 }, { $set: { Author: "Tom" } })

db.posts.updateOne({ _id:1 },{ $set: { Author: “Tom" } })

The .save() method can be used for insert and update True

Which of the following operation removes a document from MongoDB collection?deleteOne


List two methods that deletes one mongo’s document deleteOne()
Which of the following commands removes a single document that matches the condition that
Author’s name is John ?db.authors.deleteOne({ name: “John” })

You might also like