New Documents
Estimated time to read: 4 minutes
_id¶
Every document within the collection must have a unique _id
value associated with it.
When a new document is inserted, MongoDB populates the _id
field with a value that is of type ObjectId()
. This is not enforced and any type can be used within this field!
For more information on data modeling, see M320: Data Modeling course
Error Handling¶
If an attempt to import a collection into a database that contains the same data, MongoDB will throw a duplicate key error. This stops documents from being overwritten if the unique ID field is an exact match.
To overcome this, the --drop
argument can be passed during the import, which will first drop the entire collection from the database and then import the data into the namespace.
Inserting New Documents¶
There are two ways of adding documents to the database. These are:
- Using the Atlas Data Explorer
- Using
mongosh
, the Mongo Shell
Data Explorer¶
Using the Atlas Data Explorer, select the Namespace for the document to be added to the collection. Select 'Insert Document' in the UI and enter the relevant details for the new document. The GUI allows editing the new document via JSON or by the key:value pair UI.
Mongo Shell¶
Using the Mongo Shell, documents can be inserted using the insert
command. The insert
command allows inserting one or multiple documents into a collection.
Individual Documents¶
This allows creation of individual documents within a collection. There are four steps to follow to insert a document into a collection:
mongo "mongodb+srv://<username>:<password>@<cluster>.mongodb.net/admin"
- Connect to the Atlas Cluster use sample_training
- Connect the the required database db.inspections.findOne();
- Load a random document from the collection to see the layout of a document in the collection db.inspections.insert( {JSON_DATA} )
- Insert a document into the collection with the specified JSON data
Multiple Documents¶
Inserting multiple documents into a collection is similar to inserting individual documents, the difference between the two is specifying the documents within an array, for example:
db.inspections.insert([ { "test": 1 }, { "test": 2 }, { "test": 3 } ])
- This example will insert a key:value pair for each document, the _id
field value will be generated automatically.
db.inspections.insert([{ "_id": 1, "test": 1 },{ "_id": 1, "test": 2 },{ "_id": 3, "test": 3 }])
- This example inserts key:value pairs for each document, whilst also specifying the _id
value for each document.
Note
When many documents are inserted, by default, they are added in the order that they are listed in the array. This can sometimes cause errors if a duplicate _id
field value is found in the collection.
db.inspections.insert([{ "_id": 1, "test": 1 },{ "_id": 1, "test": 2 },{ "_id": 3, "test": 3 }],{ "ordered": false })
- This example uses the ordered
field to insert documents into the collection. Documents with a unique _id
field value are inserted into the collection first, if any documents to be inserted have a duplicate _id
key value, the ordered
field will produce an error for each duplicate document.
Note
If you insert a document into a collection that doesn't exist, MongoDB will automatically create the specified collection. Watch out for typos in collection names when adding documents!
Insert Order Quiz¶
Which of the following commands will successfully insert 3 new documents into an empty pets collection?
This is correct.
The _id field is not specified in any of these documents, which means that it will be created for each automatically, and it will be unique.
db.pets.insert([{ "_id": 1, "pet": "cat" },
{ "_id": 1, "pet": "dog" },
{ "_id": 3, "pet": "fish" },
{ "_id": 4, "pet": "snake" }], { "ordered": true })
This is incorrect.
There is a duplicate id issue between the "cat" and "dog" documents. While there are still 3 documents with unique _id values, the duplicate key error will appear on the second document in the array, and will prevent the operation from reaching the other documents. This will happen due to the ordered nature of this insert operation.
db.pets.insert([{ "_id": 1, "pet": "cat" },
{ "_id": 1, "pet": "dog" },
{ "_id": 3, "pet": "fish" },
{ "_id": 4, "pet": "snake" }], { "ordered": false })
This is correct.
This insert is unordered, which means that each document with a unique _id value will get inserted into the collection, which would make a total of 3 inserted documents.
db.pets.insert([{ "_id": 1, "pet": "cat" },
{ "_id": 2, "pet": "dog" },
{ "_id": 3, "pet": "fish" },
{ "_id": 3, "pet": "snake" }])
This is correct.
While there is a duplicate key error between the "fish" and "snake" documents, it occurs at the very end of the insert operation, because this insert is ordered by default. As a result the first 3 documents will get inserted and the last one will create a duplicate key error.