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