1
+ // Update a document
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,25 +12,31 @@ async function run() {
10
12
const database = client . db ( "sample_mflix" ) ;
11
13
const movies = database . collection ( "movies" ) ;
12
14
13
- // create a filter for a movie to update
15
+ // Create a filter for movies with the title "Random Harvest"
14
16
const filter = { title : "Random Harvest" } ;
15
17
16
- // this option instructs the method to create a document if no documents match the filter
18
+ /* Set the upsert option to insert a document if no documents match
19
+ the filter */
17
20
const options = { upsert : true } ;
18
21
19
- // create a document that sets the plot of the movie
22
+ // Specify the update to set a value for the plot field
20
23
const updateDoc = {
21
24
$set : {
22
25
plot : `A harvest of random numbers, such as: ${ Math . random ( ) } `
23
26
} ,
24
27
} ;
25
28
29
+ // Update the first document that matches the filter
26
30
const result = await movies . updateOne ( filter , updateDoc , options ) ;
31
+
32
+ // Print the number of matching and modified documents
27
33
console . log (
28
34
`${ result . matchedCount } document(s) matched the filter, updated ${ result . modifiedCount } document(s)` ,
29
35
) ;
30
36
} finally {
37
+ // Close the connection after the operation completes
31
38
await client . close ( ) ;
32
39
}
33
40
}
41
+ // Run the program and print any thrown errors
34
42
run ( ) . catch ( console . dir ) ;
0 commit comments