mongoDB 1
mongoDB 1
What is MongoDB?
MongoDB is a source-available, cross-platform,
document-oriented database program.
Classified as a NoSQL database product, MongoDB utilizes
JSON-like documents with optional schemas .
What is database?
Structured Data:
SET UP:
https://www.geeksforgeeks.org/how-to-install-
mongodb-on-windows/?ref=ml_lbp
FEW COMMANDS TO TEST AFTER
CONNECTIONS
show dbs:
use db:
To create a database.
show collections:
db.collection.insert():
Inserts a document or documents into a collection.
db.collection.find():
Selects documents in a collection or view and returns a
cursor to the selected documents.
Document:
Collections:
Database:
Datatype:
{
"name: Nanditha Naveen”,
“address”:{
“street”:”Jai Maruthi Nagar”,
“city”:”Chikmagalur”,
“state”:”Karnataka”
}
}
WHERE, AND, OR & CRUD
WHERE
OUTPUT
OR
The $or operator is used to specify a compound query with
multiple conditions, where at least one condition must be
satisfied for a document to match.
db.students.find({$or:[{home_city:”City
4”},{gpa:{$gt:3.0}}]});
OUTPUT
AND
The $and operator allows you to specify multiple conditions
that documents must satisfy to match the query.
OUTPUT
CRUD
• C - Create / Insert
• R - Remove
• U - update
• D - Delete
This is applicable for a Collection (Table) or a Document
(Row)
INSERT
insertOne()
• insertOne() method inserts a document into the
collection. This method inserts only one document at a
time. This method can also be used inside multi-
document transactions.
const studentData = {
“age”: 24,
“gpa”:4.5,
“home_city”:”New York”,
“blood_group”:”O+”,
“is_hotel_resident”:true
}:
UPDATE
UpdateOne()
• The updateOne() method in MongoDB updates the first
matched document within the collection based on the
given query.
• The value of the _id field remains unchanged after
updating the value. This method updates one
document at a time and can also add new fields to the
given document.
db.students.updateOne({ name: “John Doe” },
{ $set: { gpa: 4.2 }});
UpdateMany()
DeleteMany()
PROJECTION
performance.
How Does MongoDB Projection Works?
EXAMPLE 1:
OUTPUT
EXAMPLE 2 :
OUTPUT
MongoDB Projection Operators
• $slice
• $elemMatch
• $meta
1. $slice operator :
The $slice operator bounds the number of elements
that should be returned as the output of a MongoDB
projection query.
Limitations in $slice operator:
• In a nested array the $slice operator will only return
the sliced element and will not return any other item,
name.
EXAMPLE:
2. $elemMatch :
The $elemMatch operator also limits the contents
of an array to the first element that fits the given constraint.
Though, there is a minor difference from the $ operator
because the $elemMatch projection operator needs an
explicit condition argument.
Limitations of $elemMatch operator are as follows:
expressions.
EXAMPLE :
db.candidates.find({courses:
{$elemMatch:{$eq:"English"}}},{age:1,"courses.$":1})
;
OUTPUT: