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