Explain in human terms
MONGO_HOST = “172.31.90.91”
replace with your server’s private IP address
Explain in human terms
MONGO_DB = "my_db"
name of database in the MongoDB server that you want to use
db = client[MONGO_DB]
movies = db[“movies”]
Explain in human terms
result = movies.insert_one( { “title” : “Jaws” } )
result.inserted_id
What happens when you don’t assign an id to a document?
MongoDB will create one automatically
Will this work? Why/why not?
movies.insert_one( { "_id" : [ "Star Wars",
"The Empire Strikes Back",
"Return of the Jedi" ] } )No_id shouldn’t be an array
Will this work? Why/why not?
movies.insert_one( { “Star Wars” } )
no
wrong format
Will this work? Why/why not?
movies.insert_one( { "_id" : "Star Wars" } )
Yes
* not an array
* follows format
When will this not work?
result = movies.insert_many( [ { "_id" : "Batman", "year" : 1989 },
{ "_id" : "Home Alone", "year" : 1990 },
{ "_id" : "Ghostbusters", "year" : 1984 },
{ "_id" : "Ghostbusters", "year" : 1984 },
{ "_id" : "Lord of the Rings", "year" : 2001} ] )
result.inserted_idsthe second ghostbusters
What happens when an insert fails?
Ordered vs Unordered
Ordered
* will stop processing inserts upon encountering an error.
Unordered
* will still attempt all of the others.
* inserts may be executed in a different order than you specified.
How to specify an insert is unordered?
ordered = False
Define
Field
key-value pair, a MongoDB document can have several fields
Differentiate
Field name and key
same
List
ways to delete
4
movies.delete_one()
movies.delete_many()
movies.drop() or db.drop_collection("movies")What will be the result?
movies.find({"_id" : ObjectId("5b963e71175f8feddc46f1c3")}, {"title":0})movie with specified id, no title
What will be the result?
movies.find({}, {"title":1})
gets all movies and shows title
What will the results of these be?
movies.find()
movies.find({})both the same, gets all
When you use find(), MongoDB returns a pointer to the result set called?
cursor
Is cursor.hasNext() used in both mongosh and PyMongo?
mongosh only
How to sort
testcol.find().sort("a",1)
1 for ascending, -1 for descending
How to sort multiple keys?
testcol.find().sort([("a",1),("b",-1)])
Limit result & skip some results
testcol.find().sort("a",1).limit(5).skip(5)