1
+ // Count documents in a collection
2
+
1
3
import { MongoClient } from "mongodb" ;
2
4
3
- // Replace the uri string with your MongoDB deployment's connection string.
5
+ // Replace the uri string with your MongoDB deployment's connection string
4
6
const uri = "<connection string uri>" ;
5
7
6
8
const client = new MongoClient ( uri ) ;
@@ -10,21 +12,20 @@ async function run() {
10
12
const database = client . db ( "sample_mflix" ) ;
11
13
const movies = database . collection ( "movies" ) ;
12
14
13
- // Estimate the total number of documents in the collection
14
- // and print out the count.
15
+ /* Print the estimate of the number of documents in the
16
+ "movies" collection */
15
17
const estimate = await movies . estimatedDocumentCount ( ) ;
16
18
console . log ( `Estimated number of documents in the movies collection: ${ estimate } ` ) ;
17
19
18
- // Query for movies from Canada.
20
+ /* Print the number of documents in the "movies" collection that
21
+ match the specified query */
19
22
const query = { countries : "Canada" } ;
20
-
21
- // Find the number of documents that match the specified
22
- // query, (i.e. with "Canada" as a value in the "countries" field)
23
- // and print out the count.
24
23
const countCanada = await movies . countDocuments ( query ) ;
25
24
console . log ( `Number of movies from Canada: ${ countCanada } ` ) ;
26
25
} finally {
26
+ // Close the connection after the operations complete
27
27
await client . close ( ) ;
28
28
}
29
29
}
30
+ // Run the program and print any thrown exceptions
30
31
run ( ) . catch ( console . dir ) ;
0 commit comments