mongodb_commands
mongodb_commands
database Database
table Collection
index index
column field
INSERT INTO Students (name, class, roll_no) db.Students.insertOne({ name: "Jack", class:
VALUES ("mongo", 45, "A") 10, roll_no: 20 })
Column 1 Column 2
SELECT * db.people.find()
FROM people
SELECT * db.people.find(
FROM people { status: "A" }
WHERE status = "A" )
SELECT * db.people.find(
FROM people { status: { $ne: "A" } }
WHERE status != "A" )
SELECT * db.people.find(
SQL SELECT Statements MongoDB find() Statements
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
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
UPDATE db.people.update
people Many(
SQL Update Statements MongoDB updateMany() Statements
UPDATE db.people.update
people Many(
SET age = age { status: "A" } ,
+3
{ $inc: { age: 3 } }
WHERE status
)
= "A"
Name Description
$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.
$ne Matches all values that are not equal to a specified value.
$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
Geospatial
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.
$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.
$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()
Method Description
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.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.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.
$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.
$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.
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
>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
[
{
_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
}
]
[
{
_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 }
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