Mongo
Mongo
Mongo
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.
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
} )
• 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 } })
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>
}
)
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 } )
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 } )
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" } })
The .save() method can be used for insert and update True