Insert and create documents in MongoDB

Insert and create documents in MongoDB

To insert document in MongoDB we'll use the insert method. Insert method let us insert a JSON document inside of a MongoDB collection using the syntax db.collectionName.insert(JSON).

MongoDB insert Syntax

db.collection.insert(
<document or array of documents>,
{
    ordered: <boolean>,
    writeConcern: <document>
}
)

Description of parameters

Parameter Type Default value Description
ordered boolean - <Optional> true Insert documents in an ordered or unordered order. If an error occured and the value is set to true MongoDB will quit without processing the remaining documents
writeConcern document - <Optional> omit for default A document expressing the write concern.

Inserting a single document

> db.test.insert({
  name: "something",
  types: [
    "type1",
    "type2"
  ],
  nbr: 52,
  created_date: new
  Date(
  "2017-10-10"
  ),
  metadata: {
    meta1: "value1",
    meta2: "value2"
  }
})

Result

In the result look at "nInserted", it should indicate the number of inserted documents

WriteResult({ "nInserted" : 1 })

document inserted

> db.test.find();
{ "_id" : ObjectId("5e37dd95890d645061ea7dc6"), "name" : "something", "types" : [ "type1", "type2" ], "nbr" : 52, "created_date" : ISODate("2017-10-10T00:00:00Z"), "metadata" : { "meta1" : "value1", "meta2" : "value2" } }
  • If the document does not specify an _id field, then MongoDB will assign a unique ObjectId for the document before inserting. If the documents contains one it should be unique or you will get a duplicate key error.

  • Because MongoDB is schemaless the documents inside of a MongoDB collection does not need to have the same schema and fields.

Inserting multiple documents

> db.test.insert([
{
  name: "something",
  types: [
    "type1",
    "type2"
  ],
  nbr: 52,
  created_date: new
  Date(
  "2017-10-10"
  ),
  metadata: {
    meta1: "value1",
    meta2: "value2"
  }
},
{
  name: "something",
  views: 52,
  created_date: new
  Date(
  "2017-10-10"
  )
}
])

Result

BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

Documents inserted

> db.test.find();
{ "_id" : ObjectId("5e37ddbf890d645061ea7dc7"), "name" : "something", "types" : [ "type1", "type2" ], "nbr" : 52, "created_date" : ISODate("2017-10-10T00:00:00Z"), "metadata" : { "meta1" : "value1", "meta2" : "value2" } }
{ "_id" : ObjectId("5e37ddbf890d645061ea7dc8"), "name" : "something", "views" : 52, "created_date" : ISODate("2017-10-10T00:00:00Z") }

Insert method with parameters in MongoDB

Ordered parameter

To see how the ordered parameter works let's try to inserting some documents with a duplicated key. In this test the expected result is when ordered is set to true, the number of inserted documents should be only the first one because the error occured on the second insert (duplicate key error) unlike the false option where we should get two documents.

db.test.insert([
{
    _id: "hello",
    name: "something",
},
{
    _id: "hello",
    name: "error",
},
{
    _id: "hello2",
    name: "something2",
}
],
{
    ordered: true
}
)

Result when ordered set to true

The result gives us two details:

  • The number of inserted documents is one
  • The error occured is duplicate key error when _id is equal to hello

BulkWriteResult({
        "writeErrors" : [
                {
                        "index" : 1,
                        "code" : 11000,
                        "errmsg" : "E11000 duplicate key error collection: yamicode.test index: _id_ dup key: { _id: \"hello\" }",
                        "op" : {
                                "_id" : "hello",
                                "name" : "error"
                        }
                }
        ],
        "writeConcernErrors" : [ ],
        "nInserted" : 1,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

Result when ordered set to false

The result gives us two details:

  • The number of inserted documents is two, which means it did not stop even when the error occured
  • The error occured is duplicate key error when _id is equal to hello

BulkWriteResult({
        "writeErrors" : [
                {
                        "index" : 1,
                        "code" : 11000,
                        "errmsg" : "E11000 duplicate key error collection: yamicode.test index: _id_ dup key: { _id: \"hello\" }",
                        "op" : {
                                "_id" : "hello",
                                "name" : "error"
                        }
                }
        ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})