mongo db Flashcards
how is ??
db => collections (sql tables) => documents (objetos)
mongo db atlas
cluster => escalamiento vertical
// search more information
mongo query lenguage
extension del archivo
one.mongodb
find
db(“name of DB”) # si no esta creado lo crea
db.products.find() #retur all # si no esta creado lo crea
db.products.find({price:100}) #return
db.products.findOne({price:100}) #return
inside the file
use(“platzi_store”) # name DB
db.zip.find({state: “NY”}) # name collection
db.zip.find({state: “NY”}).count()
mongosh
inside
docker-compose exec mongodb bash
mongosh “mongodb://root:root123@localhost:27017/?tls=false”
show dbs // show collections
use(“platzi_store”) # name DB
db.name_collection.find({state: “NY”}) # name collection
insert
db.products.insertOne({
name: “Product 2”,
price: 5000,
})
db.products.insertOne({
_id:1,
name: “Product 1”,
price: 100,
})
error
si funciona pero solo hasta donde se genere el error
se ejecuta aun hubiera errores
db.products.drop()
db.products.insertMany([{},{}])
para que inserte todos menos los que tienenen error
db.products.insertMany([{},{},
]
,{orderd:false} #fuera del corchete jajajajaja
)
how to delete
use(“platzi_stoire”)
db.products.drop()
always get error
even you put => {orderd:false}
do a query
{
{
}
}
use(“platzi_store”);
db.inventory.find({
“item.name”: “ab”,
});
no tiene corchetes globales
SET
MODIFY && IMPROVE the same time
use(“platzi_store”);
db.procutst2.updateOne(
{ _id: 1 },
{
$set: {
name: “Smartphone 20”,
beatiful: true,
tags: [100, 200, 300],
},
}
);
INC
INCREASE
use(“platzi_store”);
db.procutst2.updateOne(
{ _id: 1 },
{
$inc: {
price: 1,
},
}
);
ObjectId
example with GET
db.procutst2.updateOne(
{ _id: ObjectId(“66132fbe”) },
{
$get: {
price: 800,
},
}
);
other example with INC
db.procutst2.updateOne(
{ _id: ObjectId(“66132fbe”) },
{
$inc: {
price: 1,
},
}
);
updateMany : set
db.zips.updateMany(
{ city: “CLEVELAND” },
{
$set: {
see: “looking for the doors of love”,
},
}
);
updateMany : inc
db.zips.updateMany(
{ city: “CLEVELAND” },
{
$inc: {
pop: 10000000
},
}
);
updateMany : rename
#change the column name
use(“sample_training”);
db.zips.updateMany(
{ city: “CLEVELAND” },
{
$rename: {
see: “see2”
},
}
);
updateMany : unset
#delete a column
use(“sample_training”);
db.zips.updateMany(
{ city: “CLEVELAND” },
{
$unset: {
see2: “”,
},
}
);
change all elements of a table
db.zips.updateMany(
{ }
{
$set: {
see333: “you are selfish ans main”,
},
}
);
db.zips.find()
$push => one element
use(“platzi_store”);
db.inventory.updateOne(
{ _id: 4 },
{
$push: {
tags: “headphone”,
},
}
);
$push => two elements
use(“platzi_store”);
db.inventory.updateMany(
{ _id: 1 },
{
$push: {
tags: {
$each: [700, 800],
},
},
}
);
$pull => one element
db.inventory.updateOne(
{ _id: 3 },
{
$pull: {
tags: 100,
},
}
);
$pull => a lot of elements
db.inventory.updateOne(
{ _id: 3 },
{
$pull: {
tags: {
$in:[“school”,200,300]
},
},
}
);
put # update.Many()
use(“platzi_store”);
db.inventory.updateMany(
{ },
{
$pus: {
tags: {
$each:[100,200]
},
},
}
);
db.inventory.find();
pull # update.Many()
use(“platzi_store”);
db.inventory.updateMany(
{ },
{
$pull: {
tags: {
$in:[100,200]
},
},
}
);
db.inventory.find();
pop # for all
# very important => you can only enter 1 or -1
use(“platzi_store”);
db.inventory.updateMany(
{},
{
$pop: {
tags: 1,
},
}
);
db.inventory.find();
upsert
Insert: Adding a new record to the database. If the record already exists, the operation will fail.
Upsert: Adding a new record to the database. If the record already exists, it will be updated with the new data instead of failing.
use(“platzi_store”);
db.iot.updateOne(
{
sensor: “one”,
date: “2022-01-01”,
},
{
$push: {
readings: 100,
},
},
{
upsert: true,
}
);
db.iot.find();
equal => $eq
implicit
no equals => $ne
use(“platzi_store”);
db.inventory.find({
qty: {
$ne: 15,
},
});
$gt => greater than
$gte => greater than equals
$lt => less than
$lte => less than equals (iquols)
use(“platzi_store”);
db.inventory.find({
qty: {
$gt: 10, # gt // gte // lt // lte
},
});
both at the same time
use(“platzi_store”);
db.inventory.find({
qty: {
$gt: 10, $lt:20
},
});
do two questions at the same time
example 1
db.inventory.find({
one:”patient,
two:”bard”
});
db.inventory.find({
“item.name”: “ab”,
qty: { $gt: 10 },
});
$gte with a $pull
use(“platzi_store”);
db.iot.updateMany(
{
sensor: “A001”,
},
{
$pull: {
readings: { $gte: 3 },
},
}
);
db.iot.find();
$ask in mongo compas => it’s like it’s inside if
{tripduration:{$lte:200},usertype:”Subscriber”}
$regex # same a regex
regex: /line/ => this word have in the line regex: /LINE/i => ignore uppercas or lowercase regex: /^line/m => the word has to start with // always add m regex: /line$/m => the word has to start with // always add m regex: /^MANY/mi => both at the same time $regex: /^Second/m => doesnt matter: \n
db.inventory.find({
“item.description”: {
$regex: /line/,
},
});
projection
- 1 to show
- 0 dont show => only use in id
example with 1
use(“sample_training”);
db.trips.find(
{ tripduration: { $gte: 400 }, usertype: “Subscriber” },
{
tripduration: 1,
}
);
example with 2
use(“sample_training”);
db.trips.find(
{ tripduration: { $gte: 400 }, usertype: “Subscriber” },
{
tripduration: 1,
_id:0
}
);
$in => is like a ‘or’
$nin
$in
use(“platzi_store”);
db.inventory.find({
qty: { $in: [20, 25] }, # qty: { $in: [“one”,”two”] },
});
$nin
use(“platzi_store”);
db.inventory.find({
qty: { $nin: [20, 25] },
});
arrays: is is enough to have one element of the array #very important
for several values
db.inventory.find({
tags: “school”,
});
=>
“tags”: [
“school”,
“book”,
“bag”,
“headphone”,
“appliance”
]
db.inventory.find({
tags: {
$in:[“one”,”two”] }
});
what if is:
// It has to be identical, order matters // tiene que ser identica
tags: [“school”],
tags: [“school”, “book”],
$all
have all the elements
db.inventory.find({
tags: {
$all: [“book”, “school”],
},
});
=>
“tags”: [
“school”,
“book”,
“bag”,
“headphone”,
“appliance”
]
$ size
array with this number of elements
use(“platzi_store”);
db.inventory.find({
tags: {
$size: 2,
},
});
=>
“tags”: [
“school”,
“book”
]
$elemMatch => use for ARRAYS with OBJECTS
[
{
id:1,
result: ACHIEVE,
},
{
id:2,
result: ACHIEVE,
},
]
example 2
db.survey.find({
results: { $elemMatch: { product: “xyz” } },
});
=>
{
“results”: [
{
“product”: “abc”,
“score”: 10
},
{
“product”: “xyz”,
“score”: 5
}
]
},
{
“results”: [
{
“product”: “abc”,
“score”: 8
},
{
“product”: “xyz”,
“score”: 7
}
]
}
db.survey.find({
results: { $elemMatch: { product: “xyz” ,score:{$gte:7}} },
});
$elemMatch: {
“person.first_name”: “Mark”,
AND implicit
AND inside ARRAY
one attribute = $in:[10,20]
more attributes = $or
the first element
db.survey.findOne()
between
$in: ["A", "B"] contains either "book " or "bag" or both A or B or A U B ===================== $all: ["A", "B"], field contains both "book " and "bag" // have the 2 elements
db.inventory.find({
tags: {
$in: [“A”, “B”],
},
});
===============================
db.inventory.find({
tags: {
$all: [“A”, “B”],
},
});
search as array :)
use(“platzi_store”);
db.inventory.find({
“tags.0”: “A”, // “tags.100”: “A”,
});
AND implicit
db.inspections.find({
sector: “Tax Preparers - 891”,
result: “Unable to Locate”,
})
$or
db.inspections.find({
$or: [
{ sector: “Tax Preparers - 891” },
{ result: “Unable to Locate” }
],
});
$nor
db.inspections.find({
$nor: [
{ sector: “Tax Preparers - 891” },
{ result: “Unable to Locate” }
],
});
$not
use(“sample_training”);
db.inspections.find({
result: {
$not: {
$regex: /unable/i,
},
},
});
use $AND & $OR
are the same
A ∩ (B U C) => (A ∩ B) U (A ∩ C)
db.routes.find({
$and: [
{ airplane: “E70” },
{ $or: [{ dst_airport: “BOG” }, { dst_airport: “BOG” }] },
],
});
$expr
example basic
compare colums (very important)
db.monthlyBudget.find({ $expr: { $gt: [“$spent”, “$budget”] } });
db.monthlyBudget.find({ $expr: { $gt: [“$spent”, 100] } });
$exp & $eq
use(“sample_training”);
db.trips.find({
$expr: {
$eq: [“$start station id”, “$end station id”],
},
});
a lot of => $exp
db.trips.find({
$expr: {
$eq: [“$start station id”, “$end station id”],
},
$expr: {
$gte: [“$bikeid”, 22000],
},
});
db.companies.find({
“relationships.0.person.last_name”: “Zuckerberg”,
},
{});
{
“relationships”: [
{ }, // return
{ },
{ }
]
},
{
“relationships”: [
{ }, // return
{ },
{ }
]
},
agregation framework
db.AAA.aggregate([
{ $match: { } },
{ $project: { } },
{ $group: { } },
]);
data analytics
agregation framework : {
mongo query language
}
agregation framework #example
db.listingsAndReviews.find(
{
amenities: “Wifi”,
},
{
price: 1,
amenities: 1,
}
);
the same
db.listingsAndReviews.aggregate([
{ $match: { amenities: “Wifi” } },
{ $project: { price: 1, amenities: 1 } },
]);
group // agregation framework
example 2 // more important
example
db.listingsAndReviews.aggregate([
{ $match: { amenities: “Wifi” } },
{ $project: { address:1} },
{ $group: {_id: “$address.country”, total: {$sum: 1} } }
]);
db.listingsAndReviews.aggregate([
{ $project: { address:1} },
{ $group: {_id: “$address.country”, total: {$sum: 1} } }
]);
=>
[
{
“_id”: “Portugal”,
“total”: 555
},
{
“_id”: “United States”,
“total”: 1222
},
{
“_id”: “Canada”,
“total”: 649
},
sort
// 1 : ascending
// -1 descending
use(“sample_training”);
db.zips
.find({ pop: { $gte: 100 } })
.sort({ pop: 1 });
limit
example basic
db.zips
.find()
.limit(2);
example with => sort
db.zips
.find({ one: { $gte: 100 } })
.sort({ one: -1})
.limit(2)
skip => starts from N
db.categories.find()
.skip(3) //
=>
[
{
“_id”: 4,
“name”: “category 4”
},
{
“_id”: 5,
“name”: “category 5”
},
{
mongo chart
dashboards