0% found this document useful (0 votes)
9 views

mongodb_commands

The document provides a comprehensive comparison between SQL and MongoDB terms, including common commands and their equivalents. It outlines CRUD operations in MongoDB, detailing how to create, read, update, and delete documents, along with examples of SQL statements and their MongoDB counterparts. Additionally, it explains the use of various operators and methods in MongoDB for querying and manipulating data.

Uploaded by

jayanthi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

mongodb_commands

The document provides a comprehensive comparison between SQL and MongoDB terms, including common commands and their equivalents. It outlines CRUD operations in MongoDB, detailing how to create, read, update, and delete documents, along with examples of SQL statements and their MongoDB counterparts. Additionally, it explains the use of various operators and methods in MongoDB for querying and manipulating data.

Uploaded by

jayanthi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

SQL Terms MongoDB Terms

database Database

table Collection

index index

column field

row BSON document or document

primary key primary key

table joins $lookup, embedded document

A column or a combination of columns, In the case of MongoDB, we are not required to


which is unique should be specified as specify any primary key, whenever any document is
the primary key in SQL. created, its _id itself acts as a primary key.

SELECT INTO NEW_TABLE $out

MERGE INTO TABLE $merge

some common SQL statements and their MongoDB equivalents:


Create and Alter commands
SQL statements MongoDB statements

CREATE TABLE Students ( id PRIMARY


KEY NOT NULL, name Varchar(20), db.createCollection ("Students")
class Number, roll_no char(2))

ALTER TABLE Students ADD db.Students.updateMany({ }, { $set: { joining_date:


joining_date DATETIME new Date() } })

ALTER TABLE Students DROP COLUMN db.Students.updateMany({ }, { $unset:


joining_date { "joining_date": "" } })

CREATE INDEX idx_user_id_asc ON


db.Students.createIndex ( { roll_no: 1 } )
Students ( roll_no )

DROP TABLE Students db.Students.drop ()


MongoDB and SQL Insert Statement

SQL Insert statement MongoDB insert statement

INSERT INTO Students (name, class, roll_no) db.Students.insertOne({ name: "Jack", class:
VALUES ("mongo", 45, "A") 10, roll_no: 20 })

SQL and Mongo DB Select Command

Column 1 Column 2

SELECT * FROM Students db.Students.find()

db.Students.find( { }, { name: "Jack", roll_no:


SELECT id, name, roll_no FROM Students
20 } )

db.Students.find( { }, { name: "Jack", roll_no:


SELECT name, roll_no FROM Students
20, _id: 0 } )

SELECT * FROM Students WHERE roll_no = 20 db.Students.find( { roll_no: 20 } )

SELECT * FROM Students WHERE roll_no != 20 db.Students.find( { roll_no: { $ne: 20 } } )

SELECT * FROM Students WHERE roll_no = 20


db.Students.find({ roll_no: 20, class: 10 })
AND class = 10

SQL and MongoDB Update Statements

SQL Update Statements MongoDB updateMany() Statements

UPDATE Students SET roll_no = 25 db.Students.updateMany( { name : "Jack" }, { $set: {


WHERE name = "Jack" roll_no : 25 } } )

UPDATE Students SET class = class + 2 db.Students.updateMany( { name : "Jack" } , { $inc:


WHERE name= "Jack" { class : 3 } } )

SQL and MongoDB Delete Statements

SQL Delete Statements MongoDB deleteMany() Statements

DELETE FROM Students WHERE name = "Jack" db.Students.deleteMany( { name: "Jack" } )

DELETE FROM Students db.Students.deleteMany( { } )


SQL SELECT Statements MongoDB find() Statements

SELECT * db.people.find()
FROM people

SELECT id, db.people.find(


user_id, { },
status { user_id: 1, status: 1 }
FROM people )

SELECT user_id, status db.people.find(


FROM people { },
{ user_id: 1, status: 1, _id: 0 }
)

SELECT * db.people.find(
FROM people { status: "A" }
WHERE status = "A" )

SELECT user_id, status db.people.find(


FROM people { status: "A" },
WHERE status = "A" { user_id: 1, status: 1, _id: 0 }
)

SELECT * db.people.find(
FROM people { status: { $ne: "A" } }
WHERE status != "A" )

SELECT * db.people.find(
SQL SELECT Statements MongoDB find() Statements

FROM people { status: "A",


WHERE status = "A" age: 50 }
AND age = 50 )

SELECT * db.people.find(
FROM people
{ $or: [ { status: "A" } , { age: 50 } ] }
WHERE status = "A"
OR age = 50 )

SELECT * db.people.find(
FROM people { age: { $gt: 25 } }
WHERE age > 25 )

SELECT * db.people.find(
FROM people { age: { $lt: 25 } }
WHERE age < 25 )

SELECT * db.people.find(
FROM people { age: { $gt: 25, $lte: 50 } }
WHERE age > 25 )
AND age <= 50

SELECT * db.people.find( { user_id:


FROM people /bc/ } )
WHERE user_id like "%bc%" -or-
db.people.find( { user_id:
{ $regex: /bc/ } } )
SQL SELECT Statements MongoDB find() Statements

SELECT * db.people.find( { user_id:


FROM people /^bc/ } )
WHERE user_id like "bc%" -or-
db.people.find( { user_id:
{ $regex: /^bc/ } } )

SELECT * db.people.find( { status: "A" } ).sort( { user_id: 1 } )


FROM people
WHERE status = "A"
ORDER BY user_id ASC

SELECT * db.people.find( { status: "A" } ).sort( { user_id: -1 } )


FROM people
WHERE status = "A"
ORDER BY user_id DESC

SELECT COUNT(*) db.people.count()


FROM people or
db.people.find().count()

SELECT COUNT(user_id) db.people.count( { user_id


:
FROM people
{ $exists: true } } )
or
db.people.find( { user_id:
{ $exists: true } } ).count()

SELECT COUNT(*) db.people.count( { age:


SQL SELECT Statements MongoDB find() Statements

FROM people { $gt: 30 } } )


WHERE age > 30 or
db.people.find( { age: { $gt: 30 } } ).count()

SELECT DISTINCT(status) db.people.aggregate(


FROM people [ { $group : { _id : "$status" } } ] )

db.people.distinct( "status" )

SELECT * db.people.findOne()
FROM people or
LIMIT 1 db.people.find().limit(1)

SELECT * db.people.find().limit(5).skip(10)
FROM people
LIMIT 5
SKIP 10

EXPLAIN SELECT * db.people.find( { status: "A" } ).explain()


FROM people
WHERE status = "A"

SQL Update Statements MongoDB updateMany() Statements

UPDATE db.people.update
people Many(
SQL Update Statements MongoDB updateMany() Statements

SET status { age: { $gt: 25 } },


= "C"
{ $set: { status:
WHERE "C" } }
age > 25
)

UPDATE db.people.update
people Many(
SET age = age { status: "A" } ,
+3
{ $inc: { age: 3 } }
WHERE status
)
= "A"

SQL Delete Statements MongoDB deleteMany() Statements

DELETE FROM db.people.deleteMany( { stat


people us: "D" } )
WHERE status
= "D"

`DELETE FROM db.people.deleteM


people any({})

Name Description

$eq Matches values that are equal to a specified value.


Name Description

$gt Matches values that are greater than a specified value.

$gte Matches values that are greater than or equal to a specified value.

$in Matches any of the values specified in an array.

$lt Matches values that are less than a specified value.

$lte Matches values that are less than or equal to a specified value.

$ne Matches all values that are not equal to a specified value.

$nin Matches none of the values specified in an array.


Logical
Name Description

$and Joins query clauses with a logical AND returns all documents that match the
conditions of both clauses.

$not Inverts the effect of a query predicate and returns documents that
do not match the query predicate.

$nor Joins query clauses with a logical NOR returns all documents that fail to match
both clauses.

$or Joins query clauses with a logical OR returns all documents that match the
conditions of either clause.
Element
Name Description

$exists Matches documents that have the specified field.

$type Selects documents if a field is of the specified type.


Evaluation
Name Description

$expr Allows use of aggregation expressions within the query language.

$jsonSchema Validate documents against the given JSON Schema.

$mod Performs a modulo operation on the value of a field and selects


documents with a specified result.

$regex Selects documents where values match a specified regular


expression.

$text Performs text search.


Note
$text provides text query capabilities for self-managed (non-Atlas)
deployments. For data hosted on MongoDB Atlas, MongoDB offers
an improved full-text query solution, Atlas Search.

$where Matches documents that satisfy a JavaScript expression.

Geospatial
Name Description

$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.

$nearSphere Returns geospatial objects in proximity to a point on a sphere. Requires a


geospatial index. The 2dsphere and 2d indexes support $nearSphere.
Array
Name Description

$all Matches arrays that contain all elements specified in the query.
Name Description

$elemMatch Selects documents if element in the array field matches all the
specified $elemMatch conditions.

$size Selects documents if the array field is a specified size.


Bitwise
Name Description

$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
Name Description

$ 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.

$meta Projects the document's score assigned during the $text operation.
Note
$text provides text query capabilities for self-managed (non-Atlas)
deployments. For data hosted on MongoDB Atlas, MongoDB offers an
improved full-text query solution, Atlas Search.

$slice Limits the number of elements projected from an array. Supports skip and
limit slices.

MongoDB Cursor
The find() method returns a cursor object which can be used to iterate the result.
The following example gets the cursor object and assign it to a variable.
var cursor = db.employees.find()

The cursor object has the following important methods:

Method Description

cursor.count() Returns the total number of documents referenced by a cursor.

cursor.forEach() Iterates the cursor to apply a JavaScript function to each document


from the cursor.

cursor.hasNext() Returns true if a cursor can iterate further to return more documents.

cursor.isExhausted() Returns true if the cursor is closed and there are no remaining objects
in the batch.

cursor.itcount() Counts the number of documents remaining in a cursor.

cursor.limit() Specify the maximum number of documents the cursor will return.

cursor.map() Applies a function to each document visited by the cursor and collects
the return values from successive applications of the function into a
Cursor object.

cursor.max() Specifies the exclusive upper bound for a specific index in order to
constrain the results of find().

cursor.min() Specifies the inclusive lower bound for a specific index in order to
constrain the results of find().

cursor.next() Returns the next document from the result set.

cursor.pretty() Display result in the readable format.

cursor.readConcern() Specifies a level of isolation for read operations.

cursor.skip() Skips the specified number of document for pagination.

cursor.sort() Specifies the order in which the query returns matching documents.
Method Description

cursor.toArray() Returns an array that contains all the documents from a cursor.

The following example shows how to use next() method in mongosh shell.
humanResourceDB> var cur = db.employees.find()

humanResourceDB> cur.next()
{
_id:1,
firstName: "John",
lastName: "King",
email: "[email protected]",
salary: 5000
}
humanResourceDB> cur.next()
{
_id:2,
firstName: "Sachin",
lastName: "T",
email: "[email protected]",
salary: 8000
}
humanResourceDB> cur.next()
{
_id:3,
firstName: "James",
lastName: "Bond",
email: "[email protected]",
salary: 7500
}
humanResourceDB> cur.next()
{
_id:4,
firstName: "Steve",
lastName: "J",
email: "[email protected]",
salary: 7000

}
humanResourceDB> cur.next()
{
_id:5,
firstName: "Kapil",
lastName: "D",
email: "[email protected]",
salary: 4500

}
humanResourceDB> cur.next()
{
_id:6,
firstName: "Amitabh",
lastName: "B",
email: "[email protected]",
salary: 7000
}
humanResourceDB> cur.next()
null
humanResourceDB> cur.next()
MongoCursorExhaustedError: Cursor is exhausted
db.collection.find().sort(document)
db.employees.find().sort({ firstName:1 })
Update Operators
The following table lists the update operators which can be used with
the updateOne() and updateMany() methods.

Method Description

$currentDate Sets the value of a field to current date, either as a Date or a Timestamp.

$inc Increments the value of the field by the specified amount.

$min Only updates the field if the specified value is less than the existing field value.

$max Only updates the field if the specified value is greater than the existing field value.

$mul Multiplies the value of the field by the specified amount.

$rename Renames a field.

$set Sets the value of a field in a document.

$setOnInsert Sets the value of a field if an update results in an insert of a document. Has no effect on
update operations that modify existing documents.

$unset Removes the specified field from a document.

CRUD operations In MongoDB

CREATE, READ, UPDATE, and DELETE actions are referred to as CRUD operations in
MongoDB. These are the basic operations used to alter data in databases. In MongoDB, the
term "CRUD operations" refers to the standard set of database operations used to work
with collections of data.
1. Create: To add new documents to a collection, use the Create operation.
2. Read: Data from a collection is retrieved using the Read operation.
3. Update: The Update operation is used to edit existing documents in a collection.
4. Delete: A collection of documents can be deleted using the Delete procedure.
Import Data from CSV File
Consider that you have D:\employeesdata.csv file which you want to import into
new employee collection. Execute the following command to import data from the CSV file.
D:\MyData> mongoimport --db test --collection employeesdata --type csv --file employees.csv --
fields _id,firstName,lastName

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


1. insertOne() - Inserts a single document into a collection.
2. insert() - Inserts one or more documents into a collection.
3. insertMany() - Insert multiple documents into a collection.
insertOne()
Example: insertOne()
Copy
db.employees.insertOne({
firstName: "John",
lastName: "King",
email: "[email protected]"
})
Output
{
acknowledged: true,
insertedId: ObjectId("616d44bea861820797edd9b0")
}
Insert _id Manually
It is not necessary to insert auto-generated _id value. You can manually specify a unique value
for the _id field, as shown below.
Example: Insert a Document
Copy
db.employees.insertOne({
_id:"1",
firstName: "John",
lastName: "King",
email: "[email protected]"
})
Output
{
acknowledged: true,
insertedId: 1
}
The following adds multiple documents using the insertMany() method.
Example: Insert a Document
Copy
db.employees.insertMany(
[
{
firstName: "John",
lastName: "King",
email: "[email protected]"
},
{
firstName: "Sachin",
lastName: "T",
email: "[email protected]"
},
{
firstName: "James",
lastName: "Bond",
email: "[email protected]"
},
])
Output
{
acknowledged: true,
insertedIds: {
'0': ObjectId("616d63eda861820797edd9b3"),
'1': ObjectId("616d63eda861820797edd9b4"),
'2': ObjectId("616d63eda861820797edd9b5")
}
}
The findOne() returns the first document from a collection if no parameter is passed.
Example: find()
Copy
db.employees.findOne()
Output
{
_id: 1,
firstName: 'John',
lastName: 'King',
email: '[email protected]',
salary: 5000
}
Example: find()
Copy
db.employees.findOne({firstName: "Kapil"})
Output
{
_id: 5,
firstName: 'Kapil',
lastName: 'D',
email: '[email protected]',
salary: 4500
}
Example: find()
Copy
db.employees.findOne({salary: {$gt: 8000}})
Output
{
_id: 4,
firstName: 'Steve',
lastName: 'J',
email: '[email protected]',
salary: 9000
}
Syntax: {field: {operator: value}}.
Ex: {salary: {$gt: 8000}}
--

>use fswd
FSWDLAB> db.createCollection("Employees")
{ ok: 1 }
FSWDLAB> db.users.insertOne({
... name: "Angela",
FSWDLAB> db.Employees.insertOne({
... name: "Angela",
... age: 27,
... });
Output:
{
acknowledged: true,
insertedId: ObjectId('66faaec8613f867dd9c73bfc')
}
FSWDLAB> db.Employees.insertMany([
... {
... name: "Angela",
... age: 27,
... },
... {
... name: "Dwight",
... age: 30,
...
... },
... {
... name: "Jim",
... age: 29,
... }
... ]);
Output:

{
acknowledged: true,
insertedIds: {
'0': ObjectId('66faaef2613f867dd9c73bfd'),
'1': ObjectId('66faaef2613f867dd9c73bfe'),
'2': ObjectId('66faaef2613f867dd9c73bff')
}
}
Read Operations

FSWDLAB> FSWDLAB> db.Employees.find()


Output:

[
{
_id: ObjectId('66faaec8613f867dd9c73bfc'),
name: 'Angela',
age: 27
},
{
_id: ObjectId('66faaef2613f867dd9c73bfd'),
name: 'Angela',
age: 27
},
{
_id: ObjectId('66faaef2613f867dd9c73bfe'),
name: 'Dwight',
age: 30
},
{ _id: ObjectId('66faaef2613f867dd9c73bff'), name: 'Jim', age: 29 }
]
FSWDLAB> db.Employees.find({ age: { $gt: 29 } }, { name: 1, age: 1 })
FSWDLAB> db.Employees.find({ age: { $gt: 29 } }, { name: 1, age: 1 })
Output:
[
{
_id: ObjectId('66faaef2613f867dd9c73bfe'),
name: 'Dwight',
age: 30
}
]

FSWDLAB> db.Employees.find({ age: { $gt: 29 } }, { name: 1, age: 1 })


Output:
[
{
_id: ObjectId('66faaef2613f867dd9c73bfe'),
name: 'Dwight',
age: 30
}
]
FSWDLAB> db.Employees.findOne({ name: "Jim" })
Output:
{ _id: ObjectId('66faaef2613f867dd9c73bff'), name: 'Jim', age: 29 }
FSWDLAB> db.Employees.updateOne({ name: "Angela" }, { $set: { email:
"[email protected]" } })
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}

FSWDLAB> db.Employees.updateMany({ age: { $lt: 30 } }, { $set: { status: "active" } })


{
acknowledged: true,
insertedId: null,
matchedCount: 3,
modifiedCount: 3,
upsertedCount: 0
}
FSWDLAB> db.Employees.find()
[
{
_id: ObjectId('66faaec8613f867dd9c73bfc'),
name: 'Angela',
age: 27,
email: '[email protected]',
status: 'active'
},
{
_id: ObjectId('66faaef2613f867dd9c73bfd'),
name: 'Angela',
age: 27,
status: 'active'
},
{
_id: ObjectId('66faaef2613f867dd9c73bfe'),
name: 'Dwight',
age: 30
},
{
_id: ObjectId('66faaef2613f867dd9c73bff'),
name: 'Jim',
age: 29,
status: 'active'
}
]
Delete Operations

FSWDLAB> db.Employees.deleteMany({ age: { $lt: 30 } })


FSWDLAB> db.Employees.deleteMany({ age: {lt:30}})
Output:

{ acknowledged: true, deletedCount: 0 }


FSWDLAB> FSWDLAB> db.Employees.find()
Output:

[
{
_id: ObjectId('66faaef2613f867dd9c73bfd'),
name: 'Angela',
age: 27,
status: 'active'
},
{
_id: ObjectId('66faaef2613f867dd9c73bfe'),
name: 'Dwight',
age: 30
},
{
_id: ObjectId('66faaef2613f867dd9c73bff'),
name: 'Jim',
age: 29,
status: 'active'
}
]
drop()
The drop() method is used to remove an entire collection. Note: This operation is
irreversible, and all data in the collection will be permanently deleted.

FSWDLAB> db.Employees.drop()
true
FSWDLAB> db.Employees.find()
Output:

FSWDLAB>
FSWDLAB> db.createCollection("Food")
{ ok: 1 }
FSWDLAB> show collections
Food
pizzas
users
FSWDLAB> db.Food.insertMany( [
... { _id: 0, type: "pepperoni", size: "small", price: 4 },
... { _id: 1, type: "cheese", size: "medium", price: 7 },
... { _id: 2, type: "vegan", size: "large", price: 8 }
... ] )
{ acknowledged: true, insertedIds: { '0': 0, '1': 1, '2': 2 } }
FSWDLAB>

FSWDLAB> db.Food.find()
[
{ _id: 0, type: 'pepperoni', size: 'small', price: 4 },
{ _id: 1, type: 'cheese', size: 'medium', price: 7 },
{ _id: 2, type: 'vegan', size: 'large', price: 8 }
]
FSWDLAB>
FSWDLAB> try {
... db.Food.bulkWrite( [
... { insertOne: { document: { _id: 3, type: "beef", size: "medium", price: 6 } } },
... { insertOne: { document: { _id: 4, type: "sausage", size: "large", price: 10 } } },
... { updateOne: {
... filter: { type: "cheese" },
... update: { $set: { price: 8 } }
... } },
... { deleteOne: { filter: { type: "pepperoni"} } },
... { replaceOne: {
... filter: { type: "vegan" },
... replacement: { type: "tofu", size: "small", price: 4 }
... }}
... ] )
... } catch( error ) {
... print( error )
... }
{
acknowledged: true,
insertedCount: 2,
insertedIds: { '0': 3, '1': 4 },
matchedCount: 2,
modifiedCount: 2,
deletedCount: 1,
upsertedCount: 0,
upsertedIds: {}
}
FSWDLAB> db.Food.find()
[
{ _id: 1, type: 'cheese', size: 'medium', price: 8 },
{ _id: 2, type: 'tofu', size: 'small', price: 4 },
{ _id: 3, type: 'beef', size: 'medium', price: 6 },
{ _id: 4, type: 'sausage', size: 'large', price: 10 }
]
FSWDLAB>
How to create a user in MongoDB

C:\Users\Administrator>mongosh
test> show users
[]
test> db.getUsers()
{ users: [], ok: 1 }
test> show users
[]
test> use admin
switched to db admin
admin> show users
[]
admin> cursor=db.system.user.find()

admin> cursor.count()
0
admin> db.createUser( { user:"SONY", pwd:"sony123", roles:[]});

{ ok: 1 }

admin> show users


[
{
_id: 'admin.SONY',
userId: UUID('95ac7f50-6d94-4c2b-a073-2f5de2446a5d'),
user: 'SONY',
db: 'admin',
roles: [],
mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
}
]
admin>

use admin
db.createUser(
{
user: “yourUserName",
pwd: "yourPassword",
roles: [ { role: "yourPermission", db: "yourDatabase" } ]
}
);
Output:
User: Robert
Password: robert
Roles: readWrite
This will produce the following output:
Successfully added user: {
"user" : "Robert",
"roles" : [
{
"role" : "readWrite",
"db" : "sample"
}
]
}
Creating users with roles:

read Allows the user to read data from any collection within
database
readAnyDatabase It is similar to read except on the local and config databases
readWrite This role provides all the privileges of the read role plus the
ability to modify data on all non-system collections

dbAdmin This role allows the user to read form and write to the
database, as well as clean, modify, compact, get profiles and
perform validations.
dbAdminAnyDatabase Same as dbAdmin except for all databases
userAdmin This role allows the user to create and modify user accounts on
the database
userAdminAnyDatabas Same as userAdmin except on the local and config databases
e

You might also like