Introduction To MongoDB and CRUD Querying
Introduction To MongoDB and CRUD Querying
MongoDB database is built to store a huge amount of data and also perform fast.
MongoDB is not a Relational Database Management System (RDBMS). It's called a "NoSQL"
database. It is opposite to SQL based databases where it does not normalize data under schemas and
tables where every table has a fixed structure. Instead, it stores data in the collections as JSON based
documents and does not enforce schemas. It does not have tables, rows, and columns as other SQL
(RDBMS) databases. It is one of the most popular and widely used NoSQL databases.
A NoSQL database provides a mechanism for storage and retrieval of data that is modeled in means
other than the tabular relations used in relational databases.
RDBMS vs MongoDB:
RDBMS has a typical schema design that shows number of tables and the relationship between these
tables whereas MongoDB is document-oriented. There is no concept of schema or relationship.
Complex transactions are not supported in MongoDB because complex join operations are not
available.
MongoDB allows a highly flexible and scalable document structure. For example, one data document
of a collection in MongoDB can have two fields whereas the other document in the same collection
can have four.
MongoDB is faster as compared to RDBMS due to efficient indexing and storage techniques.
There are a few terms that are related in both databases. What’s called Table in RDBMS is called a
Collection in MongoDB. Similarly, a Tuple is called a Document and A Column is called a Field.
MongoDB provides a default ‘_id’ (if not provided explicitly) which is a 12-byte hexadecimal number
that assures the uniqueness of every document. It is similar to the Primary key in RDBMS.
Big Data: If you have huge amount of data to be stored in tables, think of MongoDB before RDBMS
databases. MongoDB has built-in solution for partitioning and sharing your database.
Unstable Schema: Adding a new column in RDBMS is hard whereas MongoDB is schema-less. Adding
a new field does not effect old documents and will be very easy.
Distributed data: Since multiple copies of data are stored across different servers, recovery of data is
instant and safe even if there is a hardware failure.
MongoDB has been adopted as backend software by a number of major websites and services
including EA, Cisco, Shutterfly, Adobe, Ericsson, Craigslist, eBay, and Foursquare.
Advantages of MongoDB:
It is a schema-less NoSQL database. You need not to design the schema of the database when you
are working with MongoDB.
Disadvantages of MongoDB:
Installing MongoDB:
https://www.mongodb.com/docs/manual/installation/
To install a free MongoDB database server on our local Windows machine. So, click on the Product
menu -> Community Edition->MongoDB Community Server Download->Select package->Click on
Download.
InstallingMongoDB Shell
MongoDB Shell is the quickest way to connect, configure, query, and work with your MongoDB
database. It acts as a command-line client of the MongoDB server.
Note: MongoDB Shell is an open source (Apache 2.0), standalone product developed separately from
the MongoDB Server.
MongoDB Shell is already installed with MongoDB. You can find it in the installation directory where
you installed MongoDB. By default, it is "C:\Program Files\MongoDB\Server". Open the installation
folder and appropriate version folder and go to the "bin" folder. Here, "mongo.exe" is MongoDB
shell. Click on it to open the MongoDB shell, as shown below.
Click on the Product menu -> Community Edition->Tools->MongoDB Shell Download-> click on
Download.
Click on the Download button to download the installer file.
Now, click on the downloaded installer file to start the installation wizar.
Once installation completes, click the Finish button to close the wizard.
Open a new command prompt on Windows and write mongosh and press Enter. It will open the
same MongoDB shell.
You can execute MongoB commands for CRUD operations on MongoDB shell (mongo or mongosh).
For example, execute the "shows dbs" command to see all the databases on the connected
MongoDB server.
admin 41 kB
config 111 kB
local 41 kB
>db
test
Run the .editor command to execute multi-line commands. Press Ctrl + d to run a command or Ctrl +
c to cancel.
MongoDB Shell is the quickest way to connect, configure, query, and work with your MongoDB
database. It acts as a command-line client of the MongoDB server.
You can start MongoDB Shell by executing mongo or mongosh command on the command
prompt/terminal. mongosh is the new MongoDB shell with some more features than the old mongo
shell.
mongosh<commands>
The --help command display all the commands which you can use with mongo or mongosh
The show dbs command will display all the databases on the connected server.
By default, the mongosh or mongo command connects with the local MongoDB database on the
localhost:27017. So, mongosh and mongosh "mongodb://localhost:27017" are the same that
connect to a database on the localhost at port 27017.
To connect with the local database on a different port, use the --port option:
C:\>mongosh "mongodb://mymongodb.example.com:23023"
Use the --username and --authenticationDatabase command-line options to connect with the
database that requires authentication.
You can execute MongoDB commands for CRUD operations on MongoDB shell (mongo or mongosh).
Create Operations:
Creating a database
This command will create a DB but then it is actually created only if we add a collection to it.
Execute the "shows dbs" command to see all the databases on the connected MongoDB server.
Drop a database:
Step1: Switch to the database that you want to drop. You can use the use command:
use your_database_name
Step2: Once you are inside the database, run the following command to drop the database:
db.dropDatabase()
Note: Be cautious while using the dropDatabase command, as it irreversibly removes the entire
database and its data. Double-check that you are targeting the correct database before executing the
command
Collections in MongoDB
Documents: A collection is made up of MongoDB documents, which are JSON-like BSON (Binary
JSON) documents. Each document within a collection can have its own unique structure. However, it
is common to have documents with a similar structure within a collection.
Indexing: Collections can have indexes to improve query performance. Indexes in MongoDB are
similar to indexes in relational databases and are used to optimize queries and improve the speed of
data retrieval.
Atomic Operations: MongoDB supports atomic operations at the document level. This means that a
single document can be updated atomically, and the changes are visible to other operations once the
update is complete
Dynamic Creation: Collections are created dynamically when the first document is inserted into
them. You don't need to define the structure of the collection explicitly; MongoDB will create the
collection on the fly.
CRUD Operations: Collections support CRUD (Create, Read, Update, Delete) operations. You can
insert documents into a collection, query documents, update existing documents, and delete
documents.
Creating a collection:
Syntax: db.createCollection(<collection-name>);
Example: db.createCollection(“kmitstudents”);
Also, we don't need to create collection. MongoDB creates collection automatically, when you insert
some document
A collection by name kmit will be created to which a document with the data will be added.
Drop a collection:
Step1: Switch to the database that contains the collection you want to delete.
use your_database_name
Step2: Once you are inside the database, run the following command to drop the your collection :
db.COLLECTION_NAME.drop();
For example, if you want to delete a collection named "myCollection" in the "myDatabase" database,
the command would be:
use myDatabase
db.myCollection.drop()
Note: Be careful when using the drop() method, as it permanently removes the collection and its
data. Ensure that you are targeting the correct collection before executing the command, and
consider creating a backup if necessary
To insert a document into a MongoDB collection, you can use the insertOne() method or
insertMany() method or insert() method, depending on whether you want to insert a single
document or multiple documents
insert():
It has been deprecated in recent versions of MongoDB in favor of the more specific insertOne() and
insertMany() methods. These newer methods provide more clarity and better align with the
operations they perform.
Syntax: >db.COLLECTION_NAME.insert(document)
Note: In the inserted document, if we don't specify the _id parameter, then MongoDB assigns
a unique ObjectId for this document
insertOne():
Syntax: >db.COLLECTION_NAME.insertOne(document)
insertMany():
Example:
db.empDetails.insertMany(
First_Name: "Radhika",
Last_Name: "Sharma",
Age: "26",
e_mail: "[email protected]",
phone: "9000012345"
},
First_Name: "Rachel",
Last_Name: "Christopher",
Age: "27",
e_mail: "[email protected]",
phone: "9000054321"
},
First_Name: "Fathima",
Last_Name: "Sheik",
Age: "24",
e_mail: "[email protected]",
phone: "9000054321"
}])
Read operations retrieve documents from a collection; i.e. query a collection for documents.
MongoDB provides the following methods to read documents from a collection:
db.collection.find()
The find() method in MongoDB is used to query documents from a collection. It allows you to
retrieve documents that match a specified condition or criteria. The find() method returns a cursor,
which you can iterate over to access the matching documents.
selection_criteria: It specifies selection criteria. To return all documents in a collection use empty
document({}). The type of this parameter is document.
projection: It specifies the fields to return in the documents that match the selection criteria. To
return all fields in the matching documents, remove this parameter.
db.student.find({age:18})
Projection - selecting only the necessary data rather than selecting whole of the data of a document.
If a document has 5 fields and we need to show only 3, then select only 3 fields from them
_id field is always displayed while executing find() method, if we don't want this field, then we need
to set it as 0 –
db.mycol.find({},{_id:0})
db.mycol.find({},{“name":1,_id:0})
findOne()
The findOne() method in MongoDB is similar to the find() method, but it is used to retrieve a single
document that matches the specified criteria. Once a matching document is found, findOne() returns
that document.
Example: db.books.findOne({age:18})
1. updateOne() or
2. updateMany() method, or
1. updateOne()
The updateOne() method in MongoDB is used to update a single document that matches the
specified filter criteria.
Syntax:
db.COLLECTION_NAME.updateOne(
{ },
{$set: {key:value},…}
);
2. updateMany()
The updateMany() method allows you to update multiple documents that match the specified
criteria in a single operation
Syntax:
db.COLLECTION_NAME.updateMany(
},
{$set: {key:value},…}
);
Example: Write a query to update all the users' status as ‘reject’ where theusers age is less than 18.
Keys: name,uid,age,status
db.users.updateMany(
{ age: { $lt: 18 } },
$set: {status:”reject”}
)
Delete documents in MongoDB
1. db.collection.deleteOne()
2. db.collection.deleteMany()
3. db.collection.delete() ( method (has been deprecated as of MongoDB version 4.2.)
1. db.collection.deleteOne()
The deleteOne() method in MongoDB is used to delete a single document that matches the specified
filter criteria.
Syntax:
db.COLLECTION_NAME.deleteOne(
{ },
);
2. db.collection.deleteMany()
The deleteMany() method in MongoDB is used to delete all documents that matches the specified
filter criteria.
Syntax:
db.COLLECTION_NAME.deleteMany(
{ },
);
FindAndModify and Update , with upsert
– Using Update -
– db.student.findAndModify({query:{name:"Jack"},
– update:{$set:{address:"Australia"}},
– upsert:true})
If a student by name Jack exists then it will update the document, else it will insert a new document,
because upsert if set to true.
• Using Update -
Additional Information:
Comparison Operators
For comparison of different BSON type values, see the specified BSON comparison order.
$ne: Matches all values that are not equal to a specified value.
$gte: Matches values that are greater than or equal to a specified value.
$lte: Matches values that are less than or equal to a specified value.
Syntax: { field: { $lte: value } }
LogicalOperators
In MongoDB, logical operators are used in queries to combine multiple conditions, allowing you to
express complex criteria for document retrieval.
$and: Joins query clauses with a logical AND returns all documents that match the conditions of both
clauses.
Syntax:
db.COLLECTION_NAME.find(
$and: [
{<key1>:<value1>}, { <key2>:<value2>},…..
$not: Inverts the effect of a query expression and returns documents that do not match the query
expression.
Syntax:
db.COLLECTION_NAME.find(
$nor: Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
Syntax:
db.COLLECTION_NAME.find(
{
$or: Joins query clauses with a logical OR returns all documents that match the conditions of either
clause.
Syntax:
db.COLLECTION_NAME.find(
$or: [
).pretty()
Example1:
Example2 : In the following example, the compound query document selects all documents in the
collection where the status equals "A" and either qty is less than ($lt) 30 or item starts with the
character p:
ElementOperators
EvaluationOperators
$mod: Performs a modulo operation on the value of a field and selects documents with a specified
result.
GeospatialOperators
$geoIntersects: Selects geometries that intersect with a GeoJSON geometry. The 2dsphere index
supports $geoIntersects.
$geoWithin: Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes
support $geoWithin.
$near: Returns geospatial objects in proximity to a point. Requires a geospatial index. The 2dsphere
and 2d indexes support $near.
ArrayOperators
$all: Matches arrays that contain all elements specified in the query.
$elemMatch: Selects documents if element in the array field matches all the specified $elemMatch
conditions.
BitwiseOperators
$bitsAllClear: Matches numeric or binary values in which a set of bit positions all have a value of 0.
$bitsAllSet: Matches numeric or binary values in which a set of bit positions all have a value of 1.
$bitsAnyClear: Matches numeric or binary values in which any bit from a set of bit positions has a
value of 0.
$bitsAnySet: Matches numeric or binary values in which any bit from a set of bit positions has a value
of 1.
Projection Operators
$: Projects the first element in an array that matches the query condition.
$elemMatch: Projects the first element in an array that matches the specified $elemMatch condition.
$slice: Limits the number of elements projected from an array. Supports skip and limit slices.
Miscellaneous Operators
The $regex operator of MongoDB is implemented for searching any specific string from the
collection.
➢ db.books.find({"title":{$regex:/h/i}}).pretty()
➢ Starts with:
db.books.find({"title":{$regex:/^h/i}}).pretty()
➢ Ends with: