Skip to content

Commit b7894f4

Browse files
author
Chris Cho
authored
DOCSP-10446: feedback fixes for bulkwrite (#108)
* DOCSP-10446: feedback fixes for bulkwrite
1 parent 265f3a0 commit b7894f4

File tree

3 files changed

+118
-110
lines changed

3 files changed

+118
-110
lines changed

source/code-snippets/usage-examples/bulkWrite-example.js

Lines changed: 0 additions & 55 deletions
This file was deleted.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
2+
const { MongoClient } = require("mongodb");
3+
4+
// Replace the uri string with your MongoDB deployment's connection string.
5+
const uri =
6+
"mongodb+srv://<user>:<password>@<cluster-url>?w=majority";
7+
8+
const client = new MongoClient(uri);
9+
10+
async function run() {
11+
try {
12+
await client.connect();
13+
14+
const database = client.db("sample_mflix");
15+
const collection = database.collection("theaters");
16+
17+
const result = await collection.bulkWrite([
18+
{ insertOne:
19+
{
20+
"document": {
21+
location: {
22+
address: { street1: '3 Main St.', city: 'Anchorage', state: 'AK', zipcode: '99501' },
23+
}
24+
}
25+
}
26+
},
27+
{ insertOne:
28+
{
29+
"document": {
30+
location: {
31+
address: { street1: '75 Penn Plaza', city: 'New York', state: 'NY', zipcode: '10001' },
32+
}
33+
}
34+
}
35+
},
36+
{ updateMany:
37+
{
38+
"filter": { "location.address.zipcode" : "44011" },
39+
"update": { $set : { "street2" : "25th Floor" } },
40+
"upsert": true
41+
}
42+
},
43+
{ deleteOne :
44+
{ "filter" : { "location.address.street1" : "221b Baker St"} }
45+
},
46+
]);
47+
48+
console.log(result);
49+
50+
} finally {
51+
await client.close();
52+
}
53+
}
54+
run().catch(console.dir);

source/usage-examples/bulkWrite.txt

Lines changed: 64 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -12,52 +12,50 @@ Perform Bulk Operations
1212
the result object type, see the
1313
:node-api:`API documentation <BulkWriteResult.html>`.
1414

15-
:node-api:`collection.bulkWrite <Collection.html#bulkWrite>` lets you
16-
perform bulk write operations against a *single* collection. With
17-
``collection.bulkWrite()``, you specify a list of operations to perform
18-
and MongoDB then executes those operations in bulk. Bulk write supports
19-
``insertOne``, ``updateOne``, ``updateMany``, ``deleteOne``,
20-
``deleteMany``, and ``replaceOne`` operations. Refer to the method
21-
documentation for full details.
22-
23-
``bulkWrite()`` accepts the following parameters:
24-
25-
- ``operations``: specifies the bulk operations to
15+
The ``bulkWrite()`` method performs batch write operations against a
16+
*single* collection. This method reduces the number of network round trips from
17+
your application to the server which therefore increases the throughput and
18+
performance. Since you only receive the success status after the batch
19+
write returns, we recommend you use this if that meets the requirements
20+
of your use case.
21+
22+
You can specify one or more of the following write operations in
23+
``bulkWrite()``:
24+
25+
- ``insertOne``
26+
- ``updateOne``
27+
- ``updateMany``
28+
- ``deleteOne``
29+
- ``deleteMany``
30+
- ``replaceOne``
31+
32+
The ``bulkWrite()`` method accepts the following parameters:
33+
34+
- ``operations``: specifies the bulk write operations to
2635
perform. Pass each operation to ``bulkWrite()`` as an object in
27-
an array.
36+
an array. For examples that show the syntax for each write operation, see
37+
the :node-api:`bulkWrite API documentation <Collection.html#bulkWrite>`.
2838

2939
- ``options``: *optional* settings that affect the execution
30-
of the operation, such as :manual:`write concern
31-
</reference/write-concern>` and order.
40+
of the operation, such as whether the write operations should execute in
41+
sequential order and the write concern.
3242

33-
By default, MongoDB executes bulk operations one-by-one in the
43+
By default, MongoDB executes bulk write operations one-by-one in the
3444
specified order (i.e. serially). During an ordered bulk write, if
3545
an error occurs during the processing of an operation, MongoDB returns
3646
without processing the remaining operations in the list. In contrast,
3747
when ``ordered`` is ``false``, MongoDB continues to process remaining
38-
write operations in the list. Unordered operations are faster as
39-
MongoDB can execute the operations in parallel, but the results of the
40-
operation may vary. For example, a ``deleteOne`` operation run before
41-
an ``updateMany`` operation might have a different result from running
42-
it after the ``updateMany``. Refer to :manual:`Execution of Operations
43-
</reference/method/db.collection.bulkWrite/#execution-of-operations>`
44-
for more information.
45-
46-
- ``callback``: command result callback. Like other collection methods,
47-
``bulkWrite()`` returns a Promise if you do not specify a callback.
48-
The Promise resolves to a :node-api:`bulkWriteOpCallback
49-
<Collection.html#~bulkWriteOpCallback>` object containing the
50-
result of the operation.
51-
52-
If you create an index with a :manual:`unique constraint
53-
</core/index-unique>`, you might encounter a duplicate key write error
54-
during an operation. The following example shows a duplicate key error
55-
encountered when two of the users in the inserted sample dataset had the
56-
same email address.
48+
write operations in the list. Unordered operations are theoretically faster
49+
since MongoDB can execute them in parallel, but should only be used if
50+
the writes do not depend on order.
51+
52+
If you create an index with a :manual:`unique index </core/index-unique>`
53+
constraint, you might encounter a duplicate key write error during an
54+
operation in the following format:
5755

5856
.. code-block:: sh
5957

60-
Error during bulkWrite, BulkWriteError: E11000 duplicate key error collection: sample_mflix.users index: email_1 dup key: { : "[email protected]" }
58+
Error during bulkWrite, BulkWriteError: E11000 duplicate key error collection: ...
6159

6260
Similarly, if you attempt to perform a bulk write against a collection
6361
that uses :manual:`schema validation </core/schema-validation>`, you may
@@ -67,29 +65,40 @@ modified documents.
6765
Example
6866
-------
6967

70-
The following code sample performs a bulk write operation against the
71-
``users`` collection in the ``sample_mflix`` database. Specifically, the
72-
program formats the data from a ``users.json`` source file to perform a
73-
series of ``insertOne`` operations with the ``bulkWrite()`` collection
74-
method. Download the dataset here: `users.json
75-
<https://raw.githubusercontent.com/mongodb-university/universal-driver-examples/master/users.json>`_.
76-
77-
Documents in the ``users`` collection have ``email``, ``password``,
78-
and ``name`` fields, as well as the generated ``_id`` field.
79-
``users.json`` contains an array of objects that map directly to the
80-
existing fields in the collection, as in the following:
81-
82-
.. code-block:: javascript
83-
84-
{
85-
"email" : "[email protected]",
86-
"password" : "450f6704710dcf8033157978f7fbdfde",
87-
"name" : "Marie Conrad"
88-
}
68+
The following code sample performs a bulk write operation on the
69+
``theaters`` collection in the ``sample_mflix`` database. The example call
70+
to ``bulkWrite()`` includes examples of ``insertOne``, ``updateMany``, and
71+
``deleteOne`` write operations:
8972

9073
.. include:: /includes/connect-guide-note.rst
9174

92-
.. literalinclude:: /code-snippets/usage-examples/bulkWrite-example.js
75+
.. literalinclude:: /code-snippets/usage-examples/bulkWrite.js
9376
:language: javascript
9477

78+
When you run the code sample, your output should resemble the following:
9579

80+
.. code-block:: javascript
81+
82+
BulkWriteResult {
83+
result: {
84+
ok: 1,
85+
writeErrors: [],
86+
writeConcernErrors: [],
87+
insertedIds: [ [Object], [Object] ],
88+
nInserted: 2,
89+
nUpserted: 0,
90+
nMatched: 1,
91+
nModified: 1,
92+
nRemoved: 0,
93+
upserted: [],
94+
lastOp: { ts: [Timestamp], t: 17 }
95+
},
96+
insertedCount: 2,
97+
matchedCount: 1,
98+
modifiedCount: 1,
99+
deletedCount: 0,
100+
upsertedCount: 0,
101+
upsertedIds: {},
102+
insertedIds: { '0': 5ec4..., '1': 5ec4... },
103+
n: 2
104+
}

0 commit comments

Comments
 (0)