@@ -198,6 +198,85 @@ three documents. See :ref:`insert-command-output` for details.
198
198
199
199
{ "ok" : 1, "n" : 3 }
200
200
201
+
202
+ Using Insert with ``bypassDocumentValidation``
203
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
204
+
205
+ If :doc:`schema validation validationActions</core/schema-validation>`
206
+ are set to ``error``, inserts to a collection return errors for
207
+ documents that violate the schema validation rules. To insert documents
208
+ which would violate these rules set ``bypassDocumentValidation: true``.
209
+
210
+ Create the ``user`` collection with a validation rule on the ``status``
211
+ fields.
212
+
213
+ The validation rule validates that the status must be "Unknown"
214
+ or "Incomplete":
215
+
216
+ .. code-block:: javascript
217
+
218
+ db.createCollection("users", {
219
+ validator:
220
+ {
221
+ status: {
222
+ $in: [ "Unknown", "Incomplete" ]
223
+ }
224
+ }
225
+ })
226
+
227
+ Attempt to insert a document which violates the validation rule:
228
+
229
+ .. code-block:: javascript
230
+
231
+ db.runCommand({
232
+ insert: "users",
233
+ documents: [ {user: "123", status: "Active" } ]
234
+ })
235
+
236
+ The insert returns a write error message:
237
+
238
+ .. code-block:: javascript
239
+ :copyable: false
240
+ :emphasize-lines: 8,12,16
241
+
242
+ {
243
+ n: 0,
244
+ writeErrors: [
245
+ {
246
+ index: 0,
247
+ code: 121,
248
+ errInfo: {
249
+ failingDocumentId: ObjectId('6197a7f2d84e85d1cc90d270'),
250
+ details: {
251
+ operatorName: '$in',
252
+ specifiedAs: { status: { '$in': [Array] } },
253
+ reason: 'no matching value found in array',
254
+ consideredValue: 'Active'
255
+ }
256
+ },
257
+ errmsg: 'Document failed validation'
258
+ }
259
+ ],
260
+ ok: 1
261
+ }
262
+
263
+
264
+ Set ``bypassDocumentValidation : true`` and rerun the insert:
265
+
266
+ .. code-block:: javascript
267
+
268
+ db.runCommand({
269
+ insert: "users",
270
+ documents: [ {user: "123", status: "Active" } ],
271
+ bypassDocumentValidation: true
272
+ })
273
+
274
+
275
+ The operation succeeds.
276
+
277
+ To check for documents that violate schema validation rules, use the
278
+ :dbcommand:`validate` command.
279
+
201
280
.. _insert-command-output:
202
281
203
282
Output
0 commit comments