Documentos de Académico
Documentos de Profesional
Documentos de Cultura
importar JSON
mongoimport --db students --collection students --type json --file seed.json
1.-
-db.names.insert({'name':'Seba'});
WriteResult({ "nInserted" : 1 })
-db.names.find();
{ "_id" : ObjectId("57ff7f78cddc715f74d0b872"), "name" : "Seba" }
JSON
1.-Tipos de datos contemplados en JSON:
-Object
-Array
-String
-Number
BSON(Binary JSON)
Los datos que se transmiten entre el driver y la BD Mongo
-Ligeros
-Desplazable
-Eficiente
crear objetos
-var c = db.movies.find()
-c.hasNext() (Valida si tiene valores)
-c.next() (Retorna el valor del primer valor encontrado)
Creando un Proyecto Maven
-mvn archetype:generate
-enter
-enter (opcion 6)
-nombre del package
-nombre del proyecto
-version (enter)
-package (enter)
Es imposible embedir data en un document cuando la data embedida excede los 16MB
(limite de mongo)
Week 2
db.moviesScratch.insertOne({"title":"Rocky","year":"1976","imdb":"tt0075145"})
{
"acknowledged" : true,
"insertedId" : ObjectId("5806570448549b6c8dc147d4")
}
db.moviesScratch.insertOne({"title":"Rocky","year":"1976","_id":"tt0075145"})
R: { "acknowledged" : true, "insertedId" : "tt0075145" }
Puedes tener documentos con la misma data, pero distinto objectId
Creating documents
-insertOne()
-insertMany()
-update Commands("upserts") Si existe hace update, si no insert
_id (ObjectId)
-----------------------
-Todas las colecciones tienen un _id unico
-por defecto el ObjectId se crea a partir de
Reading Documents
---------------------
-db.movieDetails.find({rated: "PG-13"}).count();
152
-db.movieDetails.find({rated: "PG-13", year: 2009}).count();
8
-db.movieDetails.find({"tomato.meter" : 100}).count();
34
-db.movieDetails.find({"tomato.meter" : 100}).pretty();
-db.movieDetails.find({tomato.meter : 100}).count();//SyntaxError
para acceder a variables detro de un objeto es necesario usar comillas al referirse
a la variable
-db.movieDetails.find({"tomato.meter" : 100}).count();//SyntaxError
Equality Matches on Arrays
----------------------------
-On the entire array
-Based on any element
-Based on a specific element
-More complex matches using operators (discussed in another lesson)
**********db.movieDetails.find({"countries.1":"Sweden"}).count()//buscar en
posicion
Equality Matches
-----------------
-Scalars
-Embedded Documents
-Arrays
-Cursors
-----------
var c = db.movieDetails.find();
var doc = function() { return c.hasNext() ? c.next() : null;}
c.objsLeftInBatch(); (Validar numero de objectos en la lista despues de los c.next)
doc() (muestra sgte object del array, si no existe muestra null como se especifico)
c.objsLeftInBatch(); devuelve cero al recorrer cada next del array
-Projection
---------------
-db.movieDetails.find({rated: "G"},{title:1}).pretty()
la consulta busca los titulos de todas las peliculas con rate "G" y que al menos
tengan 1 titulo
{ "_id" : ObjectId("5692a15524de1e0ce2dfcfa3"), "title" : "Toy Story 3" }
-db.movieDetails.find({rated: "G"},{title:1, _id: 0}).pretty()
El ObjectId siempre se devuelve por defecto, si uno lo quiere omitir puede usar
(_id:0)
Comparison Operators
----------------------
-db.movieDetails.find({rated:{$ne: "UNRATED"}}).count()
-db.movieDetails.find({rated:{$in: ["G","PG"]}}).pretty()
Element Operators
------------------
$exists
-db.movieDetails.find({"tomato.meter" : { $exists : true }})
Devuelve el find si lo encuentra, no devuelve valores si no lo encuentra
$type
-db.moviesScratch.find({ "_id" : { $type: "number"}}).pretty()
$or (ó)
-db.movieDetails.find({ $or : [{ "tomato.meter" : { $gt: 100 }}, { "metacritic" :
{$gt : 88 }} ]}).pretty()
$and (y)
-db.movieDetails.find({ $and : [{ "tomato.meter" : { $gt: 90 }}, { "metacritic" :
{$gt : 80 }}]}).pretty()
-db.movieDetails.find({ $and : [{ "metacritic" : { $ne : null}},{ "metacritic" :
{ $exists : true }}]})
Regex Operators
-------------------
Array Operators
------------------------
$all
-db.movieDetails.find({ genres: { $all : [ "Animation" , "Adventure",
"Comedy"]}}).pretty()
//debe contener las 3 condiciones
$elemMatch
####db.moviesArrays.insert({boxOffice: [ { "country": "USA", "revenue": 41.3 },
{ "country": "Australia", "revenue": 2.9 },{ "country": "UK", "revenue": 10.1 },
{ "country": "Germany", "revenue": 4.3 },{ "country": "France", "revenue":
3.5 } ]})
$size
-db.movieDetails.find({ countries : { $size : 1 }}).pretty();
//devuelve todos los documentos donde exista un solo pais
Updating Documents
---------------------------
db.movieDetails.find().pretty();
updateOne:
-db.movieDetails.updateOne({ title : "Toy Story 3"}, { $set : { poster : "nueva
imagen"}})
-db.movieDetails.updateOne({ title : "Toy Story 3"}, { $set : { "tomato.meter" :
100}})
//solo actualizará el primero que encuentre dado el "criteria"
$addToSet
//agrega elementos a un array solo si no existen
{ rating: 4.5,
date: ISODate("2016-01-12T09:00:00Z"),
reviewer: "Spencer H.",
text: "comentario"} ] } } } )
-db.movieDetails.find({rated : null}).pretty()
-db.movieDetails.find({rated : "G"}).pretty()
-Actualiza todos los documentos que posean rated "g" por "UNRATED"
-db.movieDetails.updateMany( { rated: "G" },
{ $set : { rated: "UNRATED" } } )
// Better to do this.
db.movieDetails.updateMany( { rated: null },
{ $unset: { rated: "" } } )
replaceOne:
Upserts
----------------
Si el documento no es encontrado, se crea
var detail = {
"title" : "The Martian",
"year" : 2015,
"rated" : "PG-13",
"released" : ISODate("2015-10-02T04:00:00Z"),
"runtime" : 144,
"countries" : [
"USA",
"UK"
],
"genres" : [
"Adventure",
"Drama",
"Sci-Fi"
],
"director" : "Ridley Scott",
"writers" : [
"Drew Goddard",
"Andy Weir"
],
"actors" : [
"Matt Damon",
"Jessica Chastain",
"Kristen Wiig",
"Jeff Daniels"
],
"plot" : "During a manned mission to Mars, Astronaut Mark Watney is presumed
dead after a fierce storm and left behind by his crew. But Watney has survived and
finds himself stranded and alone on the hostile planet. With only meager supplies,
he must draw upon his ingenuity, wit and spirit to subsist and find a way to signal
to Earth that he is alive.",
"poster" :
"http://ia.media-imdb.com/images/M/MV5BMTc2MTQ3MDA1Nl5BMl5BanBnXkFtZTgwODA3OTI4NjE@
._V1_SX300.jpg",
"imdb" : {
"id" : "tt3659388",
"rating" : 8.2,
"votes" : 187881
},
"tomato" : {
"meter" : 93,
"image" : "certified",
"rating" : 7.9,
"reviews" : 280,
"fresh" : 261,
"consensus" : "Smart, thrilling, and surprisingly funny, The Martian offers a
faithful adaptation of the bestselling book that brings out the best in leading man
Matt Damon and director Ridley Scott.",
"userMeter" : 92,
"userRating" : 4.3,
"userReviews" : 104999
},
"metacritic" : 80,
"awards" : {
"wins" : 8,
"nominations" : 14,
"text" : "Nominated for 3 Golden Globes. Another 8 wins & 14 nominations."
},
"type" : "movie"
};
//replace one toma un filtro "imbd", e reemplaza el que encuentra, esto solo ocurre
si lo encuentra , si no no hace nada
db.movies.replaceOne(
{"imdb": detail.imdb.id},
detail);
Blog Internals
-------------------
view - ftl - freemarker
controller/model-java/spark
Goals of Normalization
-------------------------
*Free the database of modification anomalies (actualizar el mail no implica que lo
vaya actualizar en todos los documentos)
*Minimize the redesign when extending the database
*Avoid bias toward a particular access pattern (evitar cualquier tendencia a un
patron de acceso de datos)
db.teachers.insertMany([
{"_id":0, "name":"Profe 0"},
{"_id":1, "name":"Profe 1"},
{"_id":2, "name":"Profe 2"},
{"_id":3, "name":"Profe 3"}
])
db.students.ensureIndex({'teachers':1})
db.students.find({'teachers':{$all:[0,1]}})
lazy permite dejar una propiedas en demanda, no se llenara hasta que se llame el
primer getter