linkedin sandra-acebes mail google github
abrir

MongoDB

MongoDB - CRUD Operations (Create,read,update,delete) -

MONGODB -BASIC OPERATIONS-

Login to the MongoDB Atlas

In [ ]:
https://cloud.mongodb.com/v2/5c45e4dfc56c98b1ecc199dc#clusters

1) Create your Atlas Sandbox cluster:

https://cloud.mongodb.com/links/registerForAtlas


2) connect:

click on "connect to cluster"
click on "connect to the mongo shell"
copy the connection string: (for example)

mongo "mongodb+srv://cluster0xxxxx" --username m001-student
password: m001-mongodb-basics

In [ ]:
show dbs   #show databases
use video  #select database called video
db         #show current database
show collections

Basic opearations: CREATE

In [ ]:
#insert many
In [ ]:
db.movieDetails.insertMany([{"title":"saw","year":2018,"actors":"pepito"},{"title":"saw2", "year":2019, "actors":"pepito"}])

Basic operations READ(find, count)

In [ ]:
#How many documents in video.movieDetails match the filter {genres: "Comedy"}?
db.movieDetails.find({"genres":"Comedy"})
db.movieDetails.count({"genres":"Comedy"})  #749
In [ ]:
#Examples using other filters
db.movieDetails.count({"awards.wins":2,"awards.nominations":2})
db.movieDetails.find({"awards.wins":2,"awards.nominations":2}).count()
#12
db.movieDetails.find({"writers":["Ethan Coen", "Joel Coen"]}).pretty()
In [ ]:
#Logic operators
$and
Syntax: { $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
In [ ]:
#Comparison query operators (https://docs.mongodb.com/manual/reference/operator/query-comparison/)
conditions: $ne (not equal) , $exists , $eq , $gt, $gte , $in (matches any of the values) $nin (matches none of the values)
In [ ]:
#How many documents have the poster section set to null? Ignore any documents that do not contain the rating key.
db.movieDetails.find({$and: [{poster: null}, {rating: {$exists: true}}]}).count()
#answer:0
In [ ]:
db.movieDetails.find({$and: [{poster: null}, {director: {$exists: true}}]}).count()
1252
In [ ]:
db.movieDetails.find( { "director": { $ne: "Joel Coen" } }).count()
In [ ]:
db.movieDetails.find({actors: {$in: ["Jack Nicholson", "John Huston"]}}).count()
In [ ]:
db.movieDetails.find({actors: {$nin: ["Jack Nicholson", "John Huston"]},year:{$gt:2000}}).count()
In [ ]:
db.movieDetails.find({"year":{$gte:2018}})
In [ ]:
#db.collection.update(query, update, options)
In [ ]:
#Update operators
#https://docs.mongodb.com/manual/reference/operator/update/
$inc (increments), $set (replaces), $min (updates the field if the specified value is less than the existing field value.)
In [ ]:
db.movieDetails.update({'title':'saw2'},{$set:{'title':'saw_2'}})

Basic operations DELETE

In [ ]:
db.collection.deleteMany()
In [ ]:
db.movieDetails.deleteMany({"title": "saw_2"})