<commit_before>+++
date = "2015-03-19T12:53:30-04:00"
title = "CRUD Operations"
[menu.main]
  parent = "Tutorials"
  identifier = "CRUD Operations"
  weight = 40
  pre = "<i class='fa'></i>"
+++

# CRUD Operations

For a walkthrough of the main CRUD operations please refer to the
[Quick Start guide]({{< ref "quick-start/quick-start.md" >}}).

Driver CRUD operations are defined as the operations performed to create, read, update, and delete documents.
This tutorial covers both the basic CRUD methods and the specialized ``findAndModify`` based methods
as well as the new Bulk API methods for efficient bulk write operations.

<div class="pull-right">
  <input type="checkbox" checked="" class="distroPicker" data-toggle="toggle" data-on="ES2015" data-off="ES2017" data-offstyle="success">
</div>


## Write Methods

Write methods are divided into those which insert documents into a collection, those which update
documents in a collection, and those which remove documents from a collection.

### Insert Documents

The ``insertOne`` and ``insertMany`` methods exist on the ``Collection`` class and are used to insert documents into MongoDB.



<section class="javascript5"><pre><code class="hljs">
{{% myproject-connect %}}

  // Insert a single document
  db.collection('inserts').insertOne({a:1}, function(err, r) {
    assert.equal(null, err);
    assert.equal(1, r.insertedCount);

    // Insert multiple documents
    db.collection('inserts').insertMany([{a:2}, {a:3}], function(err, r) {
      assert.equal(null, err);
      assert.equal(2, r.insertedCount);

      client.close();
    });
  });
});

</code></pre></section>
<section class="javascript6 hidden"><pre><code class="hljs">
{{% js6-connect %}}

    // Insert a single document
    let r = await db.collection('inserts').insertOne({a:1});
    assert.equal(1, r.insertedCount);

    // Insert multiple documents
    var r = await db.collection('inserts').insertMany([{a:2}, {a:3}]);
    assert.equal(2, r.insertedCount);

    // Close connection
    client.close();
  } catch(err) {
    console.log(err.stack);
  }
})();
</code></pre></section>

The first ``insert`` inserts a single document into the *inserts* collection. Notice that there's no need to
explicitly create a new *inserts* collection, as the server will create it implicitly when the first document
is inserted. The method `db.createIndex` is only necessary when creating non-standard collections,
such as [capped collections](https://docs.mongodb.org/manual/core/capped-collections/) or where parameters other
than the defaults are necessary.

The ``insertOne`` and ``insertMany`` methods also accept a second argument which can be an options object. This object can have the following fields:

| Parameter | Type | Description |
| :----------| :------------- | :------------- |
| `w` | {Number/String, > -1 \|\| 'majority'} | the write concern for the operation where < 1 returns an acknowledgment of the write with not results `{ok:1}` and w >= 1 or w = 'majority' acknowledges the write with full write results. |
| `wtimeout` | {Number, 0} | set the timeout for waiting for write concern to finish (combines with w option). |
| `j` | (Boolean, default:false) | write waits for journal sync. |
| `serializeFunctions` | (Boolean, default:false) | serialize functions on an object to mongodb, by default the driver does not serialize any functions on the passed in documents. |
| `forceServerObjectId` | (Boolean, default:false) | Force server to assign _id values instead of driver. |

The following example shows how to serialize a passed-in function when writing to a
[replica set](https://docs.mongodb.org/manual/core/replica-set-members/).

<section class="javascript5"><pre><code class="hljs">
{{% myproject-connect %}}

  // Insert a single document
  db.collection('inserts').insertOne({
        a:1<commit_msg>doc: fix typeo in crud tutorial<commit_after>+++
date = "2015-03-19T12:53:30-04:00"
title = "CRUD Operations"
[menu.main]
  parent = "Tutorials"
  identifier = "CRUD Operations"
  weight = 40
  pre = "<i class='fa'></i>"
+++

# CRUD Operations

For a walkthrough of the main CRUD operations please refer to the
[Quick Start guide]({{< ref "quick-start/quick-start.md" >}}).

Driver CRUD operations are defined as the operations performed to create, read, update, and delete documents.
This tutorial covers both the basic CRUD methods and the specialized ``findAndModify`` based methods
as well as the new Bulk API methods for efficient bulk write operations.

<div class="pull-right">
  <input type="checkbox" checked="" class="distroPicker" data-toggle="toggle" data-on="ES2015" data-off="ES2017" data-offstyle="success">
</div>


## Write Methods

Write methods are divided into those which insert documents into a collection, those which update
documents in a collection, and those which remove documents from a collection.

### Insert Documents

The ``insertOne`` and ``insertMany`` methods exist on the ``Collection`` class and are used to insert documents into MongoDB.



<section class="javascript5"><pre><code class="hljs">
{{% myproject-connect %}}

  // Insert a single document
  db.collection('inserts').insertOne({a:1}, function(err, r) {
    assert.equal(null, err);
    assert.equal(1, r.insertedCount);

    // Insert multiple documents
    db.collection('inserts').insertMany([{a:2}, {a:3}], function(err, r) {
      assert.equal(null, err);
      assert.equal(2, r.insertedCount);

      client.close();
    });
  });
});

</code></pre></section>
<section class="javascript6 hidden"><pre><code class="hljs">
{{% js6-connect %}}

    // Insert a single document
    let r = await db.collection('inserts').insertOne({a:1});
    assert.equal(1, r.insertedCount);

    // Insert multiple documents
    var r = await db.collection('inserts').insertMany([{a:2}, {a:3}]);
    assert.equal(2, r.insertedCount);

    // Close connection
    client.close();
  } catch(err) {
    console.log(err.stack);
  }
})();
</code></pre></section>

The first ``insert`` inserts a single document into the *inserts* collection. Notice that there's no need to
explicitly create a new *inserts* collection, as the server will create it implicitly when the first document
is inserted. The method `db.createCollection` is only necessary when creating non-standard collections,
such as [capped collections](https://docs.mongodb.org/manual/core/capped-collections/) or where parameters other
than the defaults are necessary.

The ``insertOne`` and ``insertMany`` methods also accept a second argument which can be an options object. This object can have the following fields:

| Parameter | Type | Description |
| :----------| :------------- | :------------- |
| `w` | {Number/String, > -1 \|\| 'majority'} | the write concern for the operation where < 1 returns an acknowledgment of the write with not results `{ok:1}` and w >= 1 or w = 'majority' acknowledges the write with full write results. |
| `wtimeout` | {Number, 0} | set the timeout for waiting for write concern to finish (combines with w option). |
| `j` | (Boolean, default:false) | write waits for journal sync. |
| `serializeFunctions` | (Boolean, default:false) | serialize functions on an object to mongodb, by default the driver does not serialize any functions on the passed in documents. |
| `forceServerObjectId` | (Boolean, default:false) | Force server to assign _id values instead of driver. |

The following example shows how to serialize a passed-in function when writing to a
[replica set](https://docs.mongodb.org/manual/core/replica-set-members/).

<section class="javascript5"><pre><code class="hljs">
{{% myproject-connect %}}

  // Insert a single document
  db.collection('inserts').insertOne({
        a:1
{'fraction_non_alphanumeric': 0.13916526683033983, 'fraction_numerical': 0.012404703450058147, 'mean_word_length': 4.201612903225806, 'pattern_counts': {'":': 0, '<': 47, '<?xml version=': 0, '>': 49, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '398791', 'n_tokens_mistral': 2279, 'n_tokens_neox': 2172, 'n_words': 814}