File tree Expand file tree Collapse file tree 1 file changed +9
-0
lines changed
source/code-snippets/indexes Expand file tree Collapse file tree 1 file changed +9
-0
lines changed Original file line number Diff line number Diff line change @@ -5,12 +5,15 @@ const { MongoClient } = require("mongodb");
55const uri =
66 "mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority" ;
77
8+ // Create a new client and connect to MongoDB
89const client = new MongoClient ( uri ) ;
910
1011async function run ( ) {
1112 try {
1213 // begin-idx
14+ // Connect to the "sample_mflix" database
1315 const database = client . db ( "sample_mflix" ) ;
16+ // Access the database's "movies" collection
1417 const movies = database . collection ( "movies" ) ;
1518
1619 // Create an ascending index on the "type" and "genre" fields
@@ -20,18 +23,24 @@ async function run() {
2023 // end-idx
2124
2225 // begin-query
26+ // Define a query to find movies in the "Drama" genre
2327 const query = { type : "movie" , genre : "Drama" } ;
28+ // Define sorting criteria for the query results
2429 const sort = { type : 1 , genre : 1 } ;
30+ // Include only the type and genre fields in the query results
2531 const projection = { _id : 0 , type : 1 , genre : 1 } ;
2632
33+ // Execute the query using the defined criteria and projection
2734 const cursor = movies
2835 . find ( query )
2936 . sort ( sort )
3037 . project ( projection ) ;
3138 // end-query
3239
3340 } finally {
41+ // Close the MongoDB client connection
3442 await client . close ( ) ;
3543 }
3644}
45+ // Run the function and handle any errors
3746run ( ) . catch ( console . dir ) ;
You can’t perform that action at this time.
0 commit comments