|
| 1 | +.. _rust-insert-one-usage: |
| 2 | + |
| 3 | +================= |
| 4 | +Insert a Document |
| 5 | +================= |
| 6 | + |
| 7 | +You can insert a document into a collection by calling the `insert_one() |
| 8 | +<{+api+}/struct.Collection.html#method.insert_one>`__ method on a |
| 9 | +``Collection`` instance. |
| 10 | + |
| 11 | +You must insert a document of the same type that you parameterized your |
| 12 | +``Collection`` instance with. For example, if you parameterized your |
| 13 | +collection with the ``MyStruct`` struct, pass a ``MyStruct`` |
| 14 | +instance as a parameter to the ``insert_one()`` method to insert a |
| 15 | +document. To learn more about specifying a type parameter, see the |
| 16 | +:ref:`Collection Parameterization <rust-coll-parameterization>` section |
| 17 | +of the Databases and Collections guide. |
| 18 | + |
| 19 | +The ``insert_one()`` method returns an `InsertOneResult |
| 20 | +<{+api+}/results/struct.InsertOneResult.html>`__ type which contains the |
| 21 | +``_id`` field of the newly inserted document. |
| 22 | + |
| 23 | +To learn more about the ``insert_one()`` method, see the |
| 24 | +:ref:`rust-insert-guide` guide. |
| 25 | + |
| 26 | +Example |
| 27 | +------- |
| 28 | + |
| 29 | +This example inserts a document into the ``restaurants`` collection of |
| 30 | +the ``sample_restaurants`` database. The example uses a ``Restaurant`` |
| 31 | +struct that has ``name``, ``borough``, and ``cuisine`` fields to model |
| 32 | +documents in the collection. |
| 33 | + |
| 34 | +The following code creates a ``Restaurant`` instance and inserts it into |
| 35 | +the collection. |
| 36 | + |
| 37 | +Select the **Asynchronous** or **Synchronous** tab to see the |
| 38 | +corresponding code for each runtime: |
| 39 | + |
| 40 | +.. tabs:: |
| 41 | + |
| 42 | + .. tab:: Asynchronous |
| 43 | + :tabid: insert-one-async |
| 44 | + |
| 45 | + .. io-code-block:: |
| 46 | + :copyable: true |
| 47 | + |
| 48 | + .. input:: /includes/usage-examples/code-snippets/insert-one-async.rs |
| 49 | + :language: rust |
| 50 | + :dedent: |
| 51 | + |
| 52 | + .. output:: |
| 53 | + :language: console |
| 54 | + :visible: false |
| 55 | + |
| 56 | + Inserted a document with _id: ObjectId("...") |
| 57 | + |
| 58 | + .. tab:: Synchronous |
| 59 | + :tabid: insert-one-sync |
| 60 | + |
| 61 | + .. io-code-block:: |
| 62 | + :copyable: true |
| 63 | + |
| 64 | + .. input:: /includes/usage-examples/code-snippets/insert-one-sync.rs |
| 65 | + :language: rust |
| 66 | + :dedent: |
| 67 | + |
| 68 | + .. output:: |
| 69 | + :language: console |
| 70 | + :visible: false |
| 71 | + |
| 72 | + Inserted a document with _id: ObjectId("...") |
0 commit comments