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");
5
5
const uri =
6
6
"mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority" ;
7
7
8
+ // Create a new client and connect to MongoDB
8
9
const client = new MongoClient ( uri ) ;
9
10
10
11
async function run ( ) {
11
12
try {
12
13
// begin-idx
14
+ // Connect to the "sample_mflix" database
13
15
const database = client . db ( "sample_mflix" ) ;
16
+ // Access the database's "movies" collection
14
17
const movies = database . collection ( "movies" ) ;
15
18
16
19
// Create an ascending index on the "type" and "genre" fields
@@ -20,18 +23,24 @@ async function run() {
20
23
// end-idx
21
24
22
25
// begin-query
26
+ // Define a query to find movies in the "Drama" genre
23
27
const query = { type : "movie" , genre : "Drama" } ;
28
+ // Define sorting criteria for the query results
24
29
const sort = { type : 1 , genre : 1 } ;
30
+ // Include only the type and genre fields in the query results
25
31
const projection = { _id : 0 , type : 1 , genre : 1 } ;
26
32
33
+ // Execute the query using the defined criteria and projection
27
34
const cursor = movies
28
35
. find ( query )
29
36
. sort ( sort )
30
37
. project ( projection ) ;
31
38
// end-query
32
39
33
40
} finally {
41
+ // Close the MongoDB client connection
34
42
await client . close ( ) ;
35
43
}
36
44
}
45
+ // Run the function and handle any errors
37
46
run ( ) . catch ( console . dir ) ;
You can’t perform that action at this time.
0 commit comments