Skip to content

Latest commit

 

History

History
210 lines (179 loc) · 5.89 KB

02_inserting_documents.md

File metadata and controls

210 lines (179 loc) · 5.89 KB

Inserting documents

Each mongodb document must have a _id field which is unique. If not explicitly specified its value is auto generated by mongodb, of the type ObjectId

ObjectId

Returns a new ObjectId value. The 12-byte ObjectId value consists of:

a 4-byte timestamp value, representing the ObjectId's creation, measured in seconds since the Unix epoch a 5-byte random value a 3-byte incrementing counter, initialized to a random value While the BSON format itself is little-endian, the timestamp and counter values are big-endian, with the most significant bytes appearing first in the byte sequence.

Methods and Attributes

ObjectId() has the following attribute and methods:

ObjectId.getTimestamp() Returns the timestamp portion of the object as a Date.

ObjectId.toString() Returns the JavaScript representation in the form of a string literal "ObjectId(...)".

ObjectId.valueOf() Returns the representation of the object as a hexadecimal string. The returned string is the str attribute.

We can set our own values as well for _id, but it has to follow unique constraint

Insert Errors

Trying to insert object with existing object id

db.inspections.findOne();
{
        "_id" : ObjectId("56d61033a378eccde8a8354f"),
        "id" : "10021-2015-ENFO",
        "certificate_number" : 9278806,
        "business_name" : "ATLIXCO DELI GROCERY INC.",
        "date" : "Feb 20 2015",
        "result" : "No Violation Issued",
        "sector" : "Cigarette Retail Dealer - 127",
        "address" : {
                "city" : "RIDGEWOOD",
                "zip" : 11385,
                "street" : "MENAHAN ST",
                "number" : 1712
        }
}
db.inspections.insert({
      "_id" : ObjectId("56d61033a378eccde8a8354f"),
      "id" : "10021-2015-ENFO",
      "certificate_number" : 9278806,
      "business_name" : "ATLIXCO DELI GROCERY INC.",
      "date" : "Feb 20 2015",
      "result" : "No Violation Issued",
      "sector" : "Cigarette Retail Dealer - 127",
      "address" : {
              "city" : "RIDGEWOOD",
              "zip" : 11385,
              "street" : "MENAHAN ST",
              "number" : 1712
         }
  })

Here we get error

WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 11000,
                "errmsg" : "E11000 duplicate key error collection: sample_training.inspections index: _id_ dup key: { _id: ObjectId('56d61033a378eccde8a8354f') }"
        }
})

db.inspections.insert({
      "id" : "10021-2015-ENFO",
      "certificate_number" : 9278806,
      "business_name" : "ATLIXCO DELI GROCERY INC.",
      "date" : "Feb 20 2015",
      "result" : "No Violation Issued",
      "sector" : "Cigarette Retail Dealer - 127",
      "address" : {
              "city" : "RIDGEWOOD",
              "zip" : 11385,
              "street" : "MENAHAN ST",
              "number" : 1712
         }
  })

db.inspections.find({"id" : "10021-2015-ENFO", "certificate_number" : 9278806}).pretty()

Here we get 2 records now, with all fields same except object id

Insert Order

If we try to insert documents in a table, they are inserted in the order in which they are provided, but this causes the problem that if an error occurs while inserting even 1 documents, then all documents after it are also not inserted

For example if we run

db.inspections.insert([ { "_id": 1, "test": 1 }, { "_id": 2, "test": 2 }, { "_id": 3, "test": 3 }])

We get

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

But if we now run

db.inspections.insert([ { "_id": 1, "test": 1 }, { "_id": 4, "test": 2 }, { "_id": 5, "test": 3 }])

We get

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

So none of the elements were inserted, even though the second and third entry had unique ids

If we do not want this to happen, then we can set the ordered flag to false like

db.inspections.insert([ { "_id": 1, "test": 1 }, { "_id": 4, "test": 2 }, { "_id": 5, "test": 3 }], { "ordered": false })
BulkWriteResult({
        "writeErrors" : [
                {
                        "index" : 0,
                        "code" : 11000,
                        "errmsg" : "E11000 duplicate key error collection: sample_trainings.inspections index: _id_ dup key: { _id: 1.0 }",
                        "op" : {
                                "_id" : 1,
                                "test" : 1
                        }
                }
        ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})

Here we got an error, but the elements that were in compliance to the _id uniqueness parameter were inserted nevertheless.

Inserting to non existing collection

Suppose we run the following command

 db.collectionName.insert({ "_id": 1, "value": "Awesome" })

Even if the collection collectionName does not exist we get

WriteResult({ "nInserted" : 1 })

Mongodb by design makes a new collection if the collection you are trying to insert in does not exists.

Now if we run

show collections

we get

collectionName
inspections