TP 2 Mongo DB
TP 2 Mongo DB
Réaliser par :
Saïd Ali Abdi
Encadrer par :
2024 - 2025
1. First, connect to your MongoDB
3. Create the movies collection with a few relevant attributes. Create the
collection by inserting the documents into a non-existent collection. You
are encouraged to think and implement collections with attributes that
you find most suitable:
Result :
4. Use the find command to fetch the documents you inserted in the previous
step, that is, db.movies.find().pretty(). It should return the following output:
5. You may also like to store awards information in your movies database.
Create an awards collection with a few records. You are encouraged to think
and come up with your own collection name and attributes. Here are the
commands to insert a few sample documents in your awards collection :
Result :
6. Run the find command to get the documents from the awards collection. The
lines starting with // (a double slash) are comments, which are only for the
purpose of description; the database does not execute them as commands:
Result :
2. Documents and Data Types
Result :
2.The requirement is to return only the titles of the movies. For this, add a
projection to project only the title field and exclude the rest, including _id:
Result :
3. Now, sort the results in descending order of IMDb ratings. Add a sort()
function to the query:
Result :
4.Add the skip function and, for now, provide any value you want (3, in this
case) :
5. Next, add a limit to the query, as follows. The limit value indicates the page
size:
6. Finally, convert our resulting cursor into an array by using the toArray()
function:
7. Now that the query has been written, open a text editor and write an empty
function that accepts a genre, a page number, and a page size, as follows:
8. Copy and paste the query inside the function, assigning it to a variable, as
follows:
9. The result you will get is an array. Write the logic needed to iterate through
the elements and print the title fields, as follows:
10. The query still has hardcoded values that need to be replaced with the
variables that are received as function arguments, so put the genre and
pageSize variables in the correct places:
11. Now, you need to derive the skip value based on the page number and
page size. When the user is on the first page, the skip value should be zero. On
the second page, the skip value should be the page size. Similarly, if the user is
on the third page, the skip value should be page size multiplied by 2. Write this
logic as follows:
Now, use the newly calculated skip value in the limit function. This makes the
function complete.
4. Inserting, Updating, and Deleting
Documents
Result :
2. Find the movie Sherlock Holmes by _id and reduce the count of comments
by 3:
Result :
Result :